package main import ( "fmt" "strings" ) func main(){ //返回字元在指定字串中最後一次出現的位置 last_index := strings.LastIndex("Hello World", "l") fmt.Printf("last_index=%v\n", last_index) //last_index=9 //字串替換,類似php的str_replace,但是go的 貌似更強大 //strings.Replace("hello,welcome come go world,go to go", "golang", n) //將指定的字串替換成另一個子串,可以指定希望替換幾個,如果n=-1表示全部替換 new_str := strings.Replace("hello,welcome come go world,go to go", "go", "golang", 1) fmt.Printf("new_str=%v\n", new_str) //last_index=9new_str=hello,welcome come golang world,golang to golang new_str = strings.Replace("hello,welcome come go world,go to go", "go", "golang", 1) fmt.Printf("new_str=%v\n", new_str) //last_index=9new_str=hello,welcome come golang world,go to go //將字串按照指定字元分割成陣列,類似php中的explode str2arr := strings.Split("hello,golang,I love you", ",") fmt.Printf("str2arr型別%T,%v\n", str2arr, str2arr) //str2arr型別[]string,[hello golang I love you] for i := 0; i < len(str2arr); i++ { fmt.Printf("str2arr[%v]=%v\n", i, str2arr[i]) } //str2arr[0]=hello //str2arr[1]=golang //str2arr[2]=I love you //將字串進行大小寫轉換 str := "hello Golang" str = strings.ToLower(str) //全部轉換為小寫 fmt.Printf("last=%v", str) //last=hello golang str = strings.ToUpper(str) //全部轉換為大寫 fmt.Printf("last=%v\n", str) //last=HELLO GOLANG //將字串兩邊的空格去掉,類似php中的trim trim_str := strings.TrimSpace(" hello golang i love you ") fmt.Printf("last=%q", trim_str) //last="hello golang i love you" //將字串左右兩邊指定的字串去掉 str = strings.Trim("~#hello go lang%#~", "#~") //第二個引數可以寫多個字元 fmt.Printf("last=%v" ,str) //last=hello go lang% //將字串左邊的指定字元去掉|將字串右邊的指定字元去掉 strings.TrimLeft() | strings.TrimRight() //判斷字串是否是指定字串的開頭 b := strings.HasPrefix("http://192.168.0.1", "http") //true fmt.Printf("bool=%b" ,b) //bool= true //判斷字串止否是指定字串的結尾 strings.HasSuffix("test.png", "jpg") //false }
package main import "fmt" import "strings" func main() { //Joins 組合 s := []string{"abc", "def", "ghi", "lmn"} buf := strings.Join(s, "---") fmt.Println("buf = ", buf) // abc---def---ghi---lmn //重複次數拼接 buf = strings.Repeat("go", 3) fmt.Println("buf = ", buf) //"gogogo" //去掉空格,把元素放入切片中 s3 := strings.Fields(" are u ok? ") //fmt.Println("s3 = ", s3) for i, data := range s3 { fmt.Println(i, ", ", data) //0 , are //1 , u //2 , ok? } }