[golang]-strings.Trim使用介绍
导语:今天用strings.Trim 的时候发现自己一直搞错了他的用法 记录一下原代码s1 := "atest1.git "beego.Info("s1" + s1)// 去除.git 获取项目名beego.Info("2gitlab项目名为:" + strings.Trim(s1, ".git"))gitproj := strings.Trim(s1, ".git")beego.Info("3g
·
导语:今天用strings.Trim 的时候发现自己一直搞错了他的用法 记录一下
原代码
s1 := "atest1.git "
beego.Info("s1" + s1)
// 去除.git 获取项目名
beego.Info("2gitlab项目名为:" + strings.Trim(s1, ".git"))
gitproj := strings.Trim(s1, ".git")
beego.Info("3gitlab项目名为:" + gitproj)
本来是想做剔除的 发现和想要的结果不一样。
s1换成t开头就有问题了 开头的t也被去掉了
s1 := "test1.git "
beego.Info("s1" + s1)
// 去除.git 获取项目名
beego.Info("2gitlab项目名为:" + strings.Trim(s1, ".git"))
gitproj := strings.Trim(s1, ".git")
beego.Info("3gitlab项目名为:" + gitproj)
查阅资料如下
函数声明:
func Trim(s string, cutset string) string
官方描述:
返回将 s 前后端所有 cutset 包含的 utf-8 码值都去掉的字符串。
示例代码:
package main
import (
"fmt"
"strings"
_ "test/subpac"
)
func main(){
fmt.Println("[ !!! Achtung! Achtung! !!! ]:[]:[", strings.Trim(" !!! Achtung! Achtung! !!! ", "") ,"\b]")
fmt.Println("[ !!! Achtung! Achtung! !!! ]:[ ]:[", strings.Trim(" !!! Achtung! Achtung! !!! ", " ") ,"\b]")
fmt.Println("[ !!! Achtung! Achtung! !!! ]:[!]:[", strings.Trim(" !!! Achtung! Achtung! !!! ", "!") , "\b]")
fmt.Println("[ !!! Achtung! Achtung! !!! ]:[! ]:[", strings.Trim(" !!! Achtung! Achtung! !!! ", "! "), "\b]" )
}
输出结果:
[ !!! Achtung! Achtung! !!! ]:[]:[ !!! Achtung! Achtung! !!! ]
[ !!! Achtung! Achtung! !!! ]:[ ]:[ !!! Achtung! Achtung! !!!]
[ !!! Achtung! Achtung! !!! ]:[!]:[ !!! Achtung! Achtung! !!! ]
[ !!! Achtung! Achtung! !!! ]:[! ]:[ Achtung! Achtung]
第一行 cutset 为空(不是空格):因此输出原字符串。
第二行 cutset 为 ” “(空格):因此串首尾的两个空格字符被删除了。
第三行 cutset 为 “!” :收尾未匹配到该 cutset,因此输出原字符串。
第四行 cutset 为 “! “:首先匹配到空格,串首尾空格字符被删除,然后匹配到 “!”,继续删除首尾的各三个 “!”,于是得到该结果串。
对于字符串test1.git
先去掉t 成为est1.gi
,在去掉i,在去掉g,再去掉.
更多推荐
已为社区贡献5条内容
所有评论(0)