go中的string和strconv包
strings.HasPrefix(s, prefix string) bool 複製程式碼
HasSuffix判斷字串是否已suffix結尾:
strings.HasSuffix(s, suffix string) bool 複製程式碼
簡單的例子:
package main import ( "fmt" "strings" ) func main() { str := "This is a Golang" fmt.Println("Prefix :", strings.HasPrefix(str, "TH")) fmt.Println("Suffix :", strings.HasSuffix(str, "lang")) } 複製程式碼
輸出:
Prefix : false Suffix : true 複製程式碼
Contains判斷字串是否包含substr:
strings.Contains(s, substr string) bool 複製程式碼
Index,LastIndex判斷字串或字元在父字串中出現的位置:
strings.Index(s, str string) int strings.LastIndex(s, str string) int 複製程式碼
Index返回字串str在字串s中的位置,-1表示不包含。LastIndex返回字串str在字串s中最後出現的位置。
例子:
package main import ( "fmt" "strings" ) func main() { str := "This is a Golang" fmt.Println("hi is:", strings.Index(str, "hi")) fmt.Println("G is:", strings.Index(str, "G")) fmt.Println("ol is", strings.LastIndex(str, "ol")) fmt.Println("s is", strings.LastIndex(str, "s")) } 複製程式碼
輸出:
hi is: 1 G is: 10 ol is 11 s is 6 複製程式碼
Replace替換字串
strings.Replace(str, old, new, n) string 複製程式碼
Count統計字串出現的次數
strings.Count(s, str string) int 複製程式碼
例子:
package main import ( "fmt" "strings" ) func main() { str := "This is a Golang" fmt.Println("a count:", strings.Count(str, "a")) } 複製程式碼
輸出:
a count: 2 複製程式碼
Repeat重複字串,用於重複count次字串s,並返回一個新的字串
strings.Repeat(s, count int) string 複製程式碼
例子:
package main import ( "fmt" "strings" ) func main() { str := "This is a Golang!" newS := strings.Repeat(str, 3) fmt.Println(newS) } 複製程式碼
輸出:
This is a Golang!This is a Golang!This is a Golang! 複製程式碼
修改字串大小寫
strings.ToLower(s) string //小寫 strings.ToUpper(s) string //大寫 複製程式碼
例子:
package main import ( "fmt" "strings" ) func main() { str := "This is a Golang!" lower := strings.ToLower(str) upper := strings.ToUpper(str) fmt.Println(lower) fmt.Println(upper) } 複製程式碼
輸出:
this is a golang! THIS IS A GOLANG! 複製程式碼
修剪字串
strings.TrimSpace(s) 提供了將字串開頭和結尾的空白字元去掉,如果想去掉其他字元,可以使用strings.Trim(s, cut string) 來將開頭和結尾的cut字串,如果只是想去掉開頭或者結尾,可以使用TrimLeft,TrimRight
分割字串
strings.Field(s)將會利用1個或者多個空白字串來作為動態長度的分隔符將字串分割成若干個小塊,並返回一個slice,如果字串只包含空白字元,則返回一個長度為0的slice。 strings.Split(s, sep) 用於自定義分割符號來指定字串進行分割,返回slice。
拼接slice到字串
strings.Join將型別為string的slice使用分隔符來拼接組成一個字串:
strings.Join(sl []string, sep string) 複製程式碼
例子:
package main import ( "fmt" "strings" ) func main() { str := "This is a Golang!" sl := strings.Fields(str) fmt.Println(sl) for _, v := range sl { fmt.Println(v) } str = "1,2,3,4,5" sl = strings.Split(str, ",") fmt.Println(sl) str = strings.Join(sl, ":") fmt.Println(str) } 複製程式碼
輸出:
[This is a Golang!] This is a Golang! [1 2 3 4 5] 1:2:3:4:5 複製程式碼
從字串衝讀取內容
strings,NewReader(string)用於生成一個Reader並且讀取字串的內容,然後返回指向該Reader的指標。