Go语言strings包常用函数
1.EqualFold
函数:strings.EqualFold(s1,s2 string)
用法:检查两个字符串是否相等,不区分大小写
返回值:返回布尔值
fmt.Println(strings.EqualFold("tiger","tiger")) //true
fmt.Println(strings.EqualFold("TiGer","tiger")) //true
fmt.Println(strings.EqualFold("Tiger","ger")) //false
2.Contains
函数:strings.Contains(s1,s2 string)
用法:用于检索 s1 中是否包含字符串 s2
返回值:返回布尔值
fmt.Println(strings.Contains("hello", "ll")) //true
fmt.Println(strings.EqualFold("hello","LL")) //false
3.Count
函数:strings.Count(s1,s2 string)
用法:用于计算 s1 中包含多少个 s2 ,且不计算已经计算过的部分
返回值:返回int
fmt.Println(strings.Count("helllo", "l")) // 3
fmt.Println(strings.Count("helllo", "ll")) // 1
4.HasPrefix
函数:strings.HasPrefix(s1,s2 string)
用法:用于判断字符串 s1 是否以 s2 作为开头
返回值:返回布尔值
fmt.Println(strings.HasPrefix("hello", "hel")) // true
fmt.Println(strings.HasPrefix("hello", "el")) // false
5.HasSuffix
函数:strings.HasSuffix(s1,s2 string)
用法:用于判定字符串 s1 是否以 s2 作为结尾
返回值:返回布尔值
fmt.Println(strings.HasSuffix("hello", "llo")) // true
fmt.Println(strings.HasSuffix("hello", "ll")) // false
6.Index
函数:strings.Index(s1,s2 string)
用法:用于寻找字符串 s2 在 s1 中第一次出现的下标,如果不存在则返回-1
返回值:返回int
fmt.Println(strings.Index("hello", "ll")) // 2
fmt.Println(strings.Index("hello", "lll")) // -1
7.Join
函数:strings.Join(s1 []string,s2 string)
用法:将 s1 中的每一个字符串用字符串 s2 进行拼接,时间速度上优于直接用+拼接
返回值:返回string
fmt.Println(strings.Join([]string{"he", "llo"}, "-")) // he-llo
8.Repeat
函数:strings.Repeat(s1 string,n int)
用法:将字符串 s1 重复 n 次进行拼接
返回值:返回string
fmt.Println(strings.Repeat("hello", 2)) // hellohello
9.Replace
函数:strings.Replace(s1,s2,s3 string,n int)
用法:将字符串 s1 中的前 n 个字符串 s2 替换成 s3 ,当n = -1时则视为全部替换
返回值:返回string
fmt.Println(strings.Replace("hello", "l", "L", -1)) // heLLo
fmt.Println(strings.Replace("hello", "l", "L", 1)) // heLlo
10.Split
函数:strings.Split(s1,s2 string)
用法:将字符串 s1 中的字符串 s2 作为分隔符进行分割成多个字符串
返回值:返回 []string
fmt.Println(strings.Split("hello", "e")) //[h llo]
fmt.Println(strings.Split("he-llo", "-")) //[he llo]
11.ToLower
函数:strings.ToLower(s1 string)
用法:将字符串 s1 全部字符变为小写
返回值:返回 string
fmt.Println(strings.ToLower("HELLO")) //hello
12.ToUpper
函数:strings.ToUpper(s1 string)
用法:将字符串 s1 全部变为大写
返回值:返回 string
fmt.Println(strings.ToUpper("hello")) //HELLO
13.LastIndex
函数:strings.LastIndex(s1,s2 string)
用法:用于寻找字符串 s2 在 s1 中最后一次出现的下标,如果不存在则返回-1
返回值:返回int
fmt.Println(strings.LastIndex("hello", "l")) // 3
fmt.Println(strings.LastIndex("hello", "lll")) // -1
14.Title
函数:strings.Title(s1 string)
用法:将字符串 s1 的首字母进行大写
返回值:返回string
fmt.Println(strings.Title("hello")) //Hello
15.TrimSpace
函数:strings.TrimSpace(s1 string)
用法:去掉字符串 s1 首尾的空白字符
返回值:返回string
fmt.Println(strings.TrimSpace(" hello ")) //hello