0
点赞
收藏
分享

微信扫一扫

go-strings

大南瓜鸭 2022-02-15 阅读 98


基础数据

str := "/usr/local/redis/bin/redis.sh"

HasPrefix

是否存在前缀字符串

// false
fmt.Printf("start with /usr result=%t \n",strings.HasPrefix(str,"/usr1"))
// true
fmt.Printf("start with /usr result=%t \n",strings.HasPrefix(str,"/usr"))

HasSuffix

是否存在后缀字符串

// true
fmt.Printf("end with .sh result=%t \n",strings.HasSuffix(str,".sh"))

Contains

是否包含该字符串

// true
fmt.Printf("contains with bin result=%t \n",strings.Contains(str,"bin"))

ContainsAny


ContainsAny reports whether any Unicode code points in chars are within s.
通俗讲就是只要有1个字母存在,就返回true


// 因为存在a,所以返回true
fmt.Printf("ContainsAny with bbb result=%t \n",strings.ContainsAny(str,"fa"))

Index

相当于java的indexOf

// 返回0
fmt.Printf("Index with usr result=%d \n",strings.Index(str,"/"))

// 返回9 1个汉字3个字节
fmt.Printf("Index with usr result=%d \n",strings.Index("你好abc中国","中"))

LastIndex

相当于java的lastIndexOf

// 返回20
fmt.Printf("Index with usr result=%d \n",strings.LastIndex(str,"/"))

IndexRune

非ASCII码的字符,可以使用IndexRune函数对字符进行定位

// 返回9
fmt.Printf("Index with usr result=%d \n",strings.Index("你好abc中国","中"))

// 返回9
fmt.Printf("Index with usr result=%d \n",strings.IndexRune("你好abc中国",'中'))

Replace

定义


func Replace(s, old, new string, n int) string
n 是匹配替换第几个,如果n>0,则替换匹配的前n个
如果是0,则不会替换
如果n<0,则替换全部


demo

str1 := "name one, name two, name three, name four"
new := "Go"
old := "name"
result := strings.Replace(str1,old,new,5)

fmt.Printf("result=%s \n",result)

Repeat

// 重复n个
str2 := strings.Repeat("abc",3);
fmt.Printf("str2=%s \n",str2)

Count

出现次数

str3:= "one two three four one one two";
// 3
oneTimes := strings.Count(str3,"one");
fmt.Printf("oneTimes = %d \n",oneTimes)

twoTimes := strings.Count(str3,"two");
fmt.Printf("twoTimes = %d \n",twoTimes)

字符数统计

str5 := "你好!"
// 3
fmt.Printf("%s字符数-one=%d \n",str5,len([]rune(str5)))
// 7 字节数统计
fmt.Printf("%s字节数-two=%d \n",str5,len(str5))
// 3
fmt.Printf("%s字符数-three=%d \n",str5,utf8.RuneCountInString(str5))

大小写转化

str6:= "aBcDeF你好!"

fmt.Printf("%s小写=%s \n",str6,strings.ToLower(str6))
fmt.Printf("%s大写=%s \n",str6,strings.ToUpper(str6))



举报

相关推荐

0 条评论