package main import ( "fmt" "strings" ) func main(){ //返回字符在指定字符串中最后一次出现的位置 last_index := strings.LastIndex("Hello World", "l") fmt.Printf("last_index=%v ", 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 ", 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 ", 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 ", str2arr, str2arr) //str2arr类型[]string,[hello golang I love you] for i := 0; i < len(str2arr); i++ { fmt.Printf("str2arr[%v]=%v ", 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 ", 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? } }