strings
strings包实现了用于操作字符的简单函数
字符串是编程中最常使用的操作之一,其重要性不言而喻,接触过其它编程语言的同学应该也有感触,在Go语言中字符串的操作主要在strings和strconv包中,本位主要介绍strings包。进行过编程开发的都熟悉,字符串的操作主要有:比较,字串,字串的个数,下标,前缀,后缀,字符串转数组[go中切片],数组[go中切片]转字符串,大写,小写,去空格,替换,类型转换[strconv]包中等这些常用操作,按照这样对比着学习,对字符串的学习会事半功倍。
比较 Compare
strings.Compare(a, b string) int
对应结果
大等小
> = <
1 0 -1
包含 strings.Contains
strings.Contains(s, sub string) bool//是否包含全部字串
fmt.Println("vixnick", "via") //false
strings.ContainsAny(s, sub string) bool//包含字串中的任意个字符 Unicode code points
fmt.Println("vixnick", "via") //true
strings.ContainsRune(s string, r rune)//和ContainsAny函数类似 该函数传入rune对应 Unicode code point 一个码值
fmt.Println(strings.ContainsRune("vixname", 97))
相等 strings.EqualFild
完全相等用 ==
"abc" == "abc //true
strings.EqualFild("aBc", "AbC")// true 忽略大小写
数组:Fields/Split
str1 := "1 23 45 67 89 "
fmt.Println(strings.Fields(str1))//[1 23 45 67 89]
str1 := "1 23 45 67 89 ab, cd, 34, a, e, 34a45bv"
f := func (c rune) bool {
return !unicode.IsNumber(c)
}
fmt.Println(strings.FieldsFunc(str1, f))//[1 23 45 67 89 34 34 45]
Split
func Split(s, sep string)[]string//替换sep
func SplitAfter(s, sep string)[]string
func SplitAfterN(s, sep string, n int)[]string
func SplitN(s, sep string, n int)[]string//替换sep
前缀/后缀 HasPrefix/HasSuffix
func HasPrefix(s, prefix string) bool
func HasSuffix(s, suffix string) bool
下标 Index
func Index(s, substr string) int
func IndexAny(s, chars string) int
func IndexByte(s string, c chars) int
func IndexFunc(s string, f func(rune) bool) int
func IndexRune(s string, r rune) int
func LastIndex(s, substr string) int
func LastIndexAny(s, chars string) int
func LastIndexByte(s string, c byte) int
func LastIndexFunc(s string, f func(rune) bool) int
切片转字符串
slice := []string{"12", "34", "56"}
fmt.Println(strings.Join(slice, "-"))//12-34-56
map
func Map(mapping func(rune) rune, s string) string
遍历s的妹子码点,传入mapping进行操作替换
rot13 := func(r rune) rune {
switch {
case r >= 'A' && r <= 'Z':
return r + 32
case r >= 'a' && r <= 'z':
return r - 32
}
return r
}
fmt.Println(strings.Map(rot13, "'Twas brillig and the slithy gopher..."))
//'tWAS BRILLIG AND THE SLITHY GOPHER...
替换 replace
func Replace(s, old, new string, n int) string//n < 0 等价于ReplaceAll, n>0则替换对应个数
func ReplaceAll(s, old, new string) string
大小写
func ToUpper(s string) string
func ToLower(s string) string
trim
func Trim(s string, cutset string) string
func TrimFunc(s string, f func(rune)bool) string
func TrimLeft(s string, cutset string) string
func TrimLeftFunc(s string, f func(rune)bool) string
func TrimPrefix(s string, cutset string) string
func TrimRight(s string, cutset string) string
func TrimRightFunc(s string, f func(rune)bool) string
func TrimSpace(s string, cutset string) string
func TrimSuffix(s string, cutset string) string
注意:
带函数将码点全部遍历进行函数操作
网友评论