下面这些函数来自于strings包,这里介绍一些我平常经常用到的函数,更详细的请参考官方的文档。
一、字符串操作常用函数介绍
1、Contains
func Contains(s, substr string) bool
功能:字符串s中是否包含substr,返回bool值
示例:
fmt.Println(strings.Contains("seafood", "foo"))
fmt.Println(strings.Contains("seafood", "bar"))
fmt.Println(strings.Contains("seafood", ""))
fmt.Println(strings.Contains("", ""))
执行结果:
true
false
true
true
2、Join
func Join(a \[\]string, sep string) string
功能:字符串链接,把slice a通过sep链接起来
示例:
s := \[\]string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
执行结果:
foo, bar, baz
3、Index
func Index(s, sep string) int
功能:在字符串s中查找sep所在的位置,返回位置值,找不到返回-1
示例:
fmt.Println(strings.Index("chicken", "ken"))
fmt.Println(strings.Index("chicken", "dmr"))
执行结果:
4
-1
4、Repeat
func Repeat(s string, count int) string
功能:重复s字符串count次,最后返回重复的字符串
示例:
fmt.Println("ba" + strings.Repeat("na", 2))
执行结果:
banana
5、Replace
func Replace(s, old, new string, n int) string
功能:在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换
示例:
fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
执行结果:
oinky oinky oink
moo moo moo
6、Split
func Split(s, sep string) \[\]string
功能:把s字符串按照sep分割,返回slice
示例:
fmt.Printf("%q\\n", strings.Split("a,b,c", ","))
fmt.Printf("%q\\n", strings.Split("a man a plan a canal panama", "a "))
fmt.Printf("%q\\n", strings.Split(" xyz ", ""))
fmt.Printf("%q\\n", strings.Split("", "Bernardo O'Higgins"))
#执行结果:
\["a" "b" "c"\]
\["" "man " "plan " "canal panama"\]
\[" " "x" "y" "z" " "\]
\[""\]
7、Trim
func Trim(s string, cutset string) string
功能:在s字符串的头部和尾部去除cutset指定的字符串
示例:
fmt.Printf("\[%q\]", strings.Trim(" !!! Achtung !!! ", "! "))
执行结果:
\["Achtung"\]
8、Fields
示例:
func Fields(s string) \[\]string
功能:去除s字符串的空格符,并且按照空格分割返回slice
执行结果:
Fields are: \["foo" "bar" "baz"\]
以上应用综合示例:
package main
import (
"fmt"
"strings"
)
func main() {
//"hellogo"中是否包含"hello", 包含返回true, 不包含返回false
fmt.Println(strings.Contains("hellogo", "hello"))
fmt.Println(strings.Contains("hellogo", "abc"))
//Joins 组合
s := \[\]string{"abc", "hello", "mike", "go"}
buf := strings.Join(s, "x")
fmt.Println("buf = ", buf)
//Index, 查找子串的位置
fmt.Println(strings.Index("abcdhello", "hello"))
fmt.Println(strings.Index("abcdhello", "go")) //不包含子串返回-1
//重复多少次,这里重复3次
buf = strings.Repeat("go", 3)
fmt.Println("buf = ", buf) //"gogogo"
//Split 以指定的分隔符拆分
buf = "hello@abc@go@mike"
s2 := strings.Split(buf, "@")
fmt.Println("s2 = ", s2)
//Trim去掉两头的字符
buf = strings.Trim(" are u ok? ", " ") //去掉2头空格
fmt.Printf("buf = #%s#\\n", buf)
//去掉空格,把元素放入切片中
s3 := strings.Fields(" are u ok? ")
//fmt.Println("s3 = ", s3)
for i, data := range s3 {
fmt.Println(i, ", ", data)
}
}
执行结果:
true
false
buf = abcxhelloxmikexgo
4
-1
buf = gogogo
s2 = \[hello abc go mike\]
buf = #are u ok?#
0 , are
1 , u
2 , ok?