web开发时常要对字符串处理,特记录以下函数。
copy自:build-web-application-with-golang
- 字符串s中是否包含substr
func Contains(s, substr string) bool
- 字符串s中是否包含substr
fmt.Println(strings.Contains("seafood", "foo"))
fmt.Println(strings.Contains("seafood", "bar"))
fmt.Println(strings.Contains("seafood", ""))
fmt.Println(strings.Contains("", ""))
//Output:
//true
//false
//true
//true
- 2.字符串链接
func Join(a []string, sep string) string
s := []string{"foo", "bar", "baz"}
fmt.Println(strings.Join(s, ", "))
//Output:foo, bar, baz
- 3.在字符串s中查找sep所在的位置,返回位置值,找不到返回-1
func Index(s, sep string) int
fmt.Println(strings.Index("chicken", "ken"))
fmt.Println(strings.Index("chicken", "dmr"))
//Output:4
//-1
- 4.重复s字符串count次,最后返回重复的字符串
func Repeat(s string, count int) string
fmt.Println("ba" + strings.Repeat("na", 2))
//Output:banana
- 5.在s字符串中,把old字符串替换为new字符串,n表示替换的次数,小于0表示全部替换
func Replace(s, old, new string, n int) string
fmt.Println(strings.Replace("oink oink oink", "k", "ky", 2))
fmt.Println(strings.Replace("oink oink oink", "oink", "moo", -1))
//Output:oinky oinky oink
//moo moo moo
- 6.把s字符串按照sep分割,返回slice
func Split(s, sep string) []string
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"))
//Output:["a" "b" "c"]
//["" "man " "plan " "canal panama"]
//[" " "x" "y" "z" " "]
//[""]
- 7.在s字符串的头部和尾部去除cutset指定的字符串
func Trim(s string, cutset string) string
fmt.Printf("[%q]", strings.Trim(" !!! Achtung !!! ", "! "))
//Output:["Achtung"]
- 8.去除s字符串的空格符,并且按照空格分割返回slice
func Fields(s string) []string
fmt.Printf("Fields are: %q", strings.Fields(" foo bar baz "))
//Output:Fields are: ["foo" "bar" "baz"]
有疑问加站长微信联系(非本文作者)