1.判斷字符串str是不是以prefix開頭code
strings.HasPrefix(s string,prefix string) bool字符串
func main() { str := "liuhaizhuang" prefix := "liu" res := strings.HasPrefix(str, prefix) fmt.Println(res) } // 結果輸出:true
2.判斷字符串str是不是以suffix結尾string
strings.HasSuffix(str string,suffix string) boolit
func main() { str := "liuhaizhuang" prefix := "zhuang" res := strings.HasSuffix(str, prefix) fmt.Println(res) } // 結果輸出:true
3.判斷s在str中首次出現的位置,若是沒有出現返回-1ast
strings.Index(str string,s string) intim
func main() { str := "liuhaizhuang" s := "hai" res := strings.Index(str, s) fmt.Println(res) } // 輸出:3
4.判斷s在str中最後一次出現的位置,若是沒有出現返回-1co
strings.LastIndex(str tring, s string) int字符
func main() { str := "liuhaizhuang" s := "h" res := strings.LastIndex(str, s) fmt.Println(res) } // 輸出:7
5.字符串替換,將str中的old字符串替換爲newStr字符串,返回替換後的結果,n參數爲替換次數,n<0表示無限次new
strings.Replace(str string,old string,newStr string,n int) string參數
func main() { str := "liuhaizhuangliu" newStr := "huang" res := strings.Replace(str, "liu", newStr, 1) fmt.Println(res) } // 輸出:huanghaizhuangliu
6.返回str中substr出現的次數
strings.Count(str string,substr string) int
func main() { str := "liuhaizhuangliu" substr := "h" res := strings.Count(str, substr) fmt.Println(res) } // 輸出:2
7.返回重複count次的str
strings.Repeat(str string,count int) string
func main() { str := "liu" count := 3 res := strings.Repeat(str, count) fmt.Println(res) } // 輸出:liuliuliu
8.把str所有轉換爲小寫
strings.ToLower(str string) string
func main() { str := "Liu" res := strings.ToLower(str) fmt.Println(res) } // 輸出:liu
9.把str所有轉換爲大寫
strings.ToUpper(str string) string
func main() { str := "Liu" res := strings.ToUpper(str) fmt.Println(res) } // 輸出:LIU
10.去掉收尾空格符
strings.TrimSpace(str string) string
func main() { str := " Liu " res := strings.TrimSpace(str) fmt.Println(res) } // 輸出:Liu
11.去掉str兩邊的cut字符串
strings.Trim(str string,cut string) string
func main() { str := "liuhaizhuang" res := strings.Trim(str, "g") fmt.Println(res) } // 輸出:liuhaizhuan
12.去掉str左邊的cut字符串
strings.TrimLeft(str string,cut string) string
func main() { str := "liuhaizhuang" res := strings.TrimLeft(str, "l") fmt.Println(res) } // 輸出:iuhaizhuang
13.去掉str右邊的cut字符串
strings.TrimRight(str string,cut string) string
func main() { str := "liuhaizhuang" res := strings.TrimRight(str, "g") fmt.Println(res) } // 輸出:liuhaizhuan
14.以空格做爲分隔符,將str分隔成切片
strings.Fields(str string) []string
func main() { str := "liu hai zhuang" res := strings.Fields(str) fmt.Println(res) } // 輸出 [liu hai zhuang]
15.以split做爲分隔符,將str分隔成切片
strings.Split(str string,split string) []string
func main() { str := "liu-hai-zhuang" res := strings.Split(str, "-") fmt.Println(res) } // 輸出:[liu hai zhuang]
16.用sep把slice中的全部元素鏈接成字符串
strings.Join(slice []string,sep string) string
func main() { slice := []string{"liu", "hai", "zhuang"} res := strings.Join(slice, "-") fmt.Println(res) } // 輸出:liu-hai-zhuang