[TOC] ## strings.Contains 是否存在某个字符或子串 ``` strings.Contains("hello", "ll") //true strings.ContainsAny("hellon你好", "llo") //true strings.ContainsRune("aardvark", rune('k')) //true ``` ## strings.Count 子串出现次数(字符串匹配) ``` strings.Count("hello word", "l") //2 ``` ## 字符串分割 ### Fields 和 FieldsFunc 切割空格等 ``` strings.Fields(" hello word a b bc")) //[hello word a b bc] strings.FieldsFunc(" hello word a b bc", unicode.IsSpace) //[hello word a b bc] strings.FieldsFunc("1a2332b3c3d4f3g5h", unicode.IsNumber) //[a b c d f g h] ``` ### Split 和 SplitAfter、 SplitN 和 SplitAfterN ``` strings.Split("foo,bar,baz", ",") //["foo" "bar" "baz"] strings.SplitAfter("foo,bar,baz", ",") //["foo," "bar," "baz"] strings.SplitN("foo,bar,baz", ",", 2) //["foo" "bar,baz"] ``` ## strings.HasPrefix字符串是否有某个前缀或后缀 ``` strings.HasPrefix("hello word", "he") //true strings.HasSuffix("hello word", "ord") //true ``` ## Index字符或子串在字符串中出现的位置 ``` strings.Index("helli wrd", "wrd") //6 //中文所在位置 const s = "a你b好c啊" index := strings.Index(s, "啊") utf8.RuneCountInString(s[:index])//4 ``` ## strings.Join 字符串并接 ``` strings.Join([]string{"name=xxx", "age=xx"}, "&") ``` ## Repeat 字符串重复几次 `strings.Repeat("ab", 2) //abab` ## Replace 字符串子串替换 ``` strings.Replace("oink oink oink", "k", "ky", 2) //oinky oinky oink 替换两个 //当第三个参数小于0 全部替换 strings.Replace("oink oink oink", "k", "ky", -1) //oinky oinky oinky ``` ## strings.NewReader() ``` reader := strings.NewReader("你好abc") p := make([]byte, 6) fmt.Println(reader.Read(p)) //你好 fmt.Println(reader.Len()) //3 fmt.Println(reader.Size()) //9 fmt.Printf("%s", p) ```