1、统计字符串的长度,按字节len(str)
// golang的编码统一为utf-8,(ascli的字符(字母和数字)占一个字节,汉字占三个字节) str := "hello上海" fmt.Println("str len=", len(str))
输出:
str len= 11
2、字符串遍历,同时处理有中文的问题r:=[]rune(str)
str := "hello上海" r := []rune(str) for index, value := range r { fmt.Printf("index=%d,value=%c\n", index, value) }
输出:
index=0,value=h index=1,value=e index=2,value=l index=3,value=l index=4,value=o index=5,value=上 index=6,value=海
3、字符串转整数
str := "123456" result, err := strconv.Atoi(str) if err != nil { fmt.Println("转换错误,", err) } else { fmt.Printf("result的类型为%T,result=%d\n", result, result) }
4、整数转字符串
num := 123456 result := strconv.Itoa(num) fmt.Printf("result的类型为%T,result=%v\n", result, result)
5、字符串转[]byte、var bytes = []byte(str)
var bytes = []byte("hello go")
6、[]byte转字符串、str:=string([]byte{[104 101 108 108 111 32 103 111]})
str := string([]byte{104, 101, 108, 108, 111, 32, 103, 111})
7、查找子串是否在指定的字符串中:strings.Contains("hello go","go")
b := strings.Contains("hello go", "go")
8、统计一个字符串有几个指定的子串:strings.Count("adfcaaafgxcda","a")
num := strings.Count("adfcaaafgxcda", "a")
9、不区分大小写的字符串比较(==是区分字母大小写),strings.EqualFold("aGB", "AGB")
b1 := strings.EqualFold("aGB", "AGB") b2 := ("aGB" == "AGB")
10、返回子串在字符串第一次出现的index值,如果没有返回-1,strings.Index("asdfhjjvghja", "jj")
index1 := strings.Index("aabbaaddbaacc", "aa") index2 := strings.Index("aabbaaddbaacc", "gg")
11、返回子串在字符串最后一次出现的index,如果没有返回-1,strings.LastIndex("aabbaaddbaacc", "aa")
index1 := strings.LastIndex("aabbaaddbaacc", "aa") index2 := strings.LastIndex("aabbaaddbaacc", "gg")
12、将指定的子串替换成另外一个子串,strings.Replace("aabbaaddbaacc", "aa", "gg", n),可以指定你替换几个,如果n=-1表示全部替换
str1 := strings.Replace("aabbaaddbaacc", "aa", "gg", -1) str2 := strings.Replace("aabbaaddbaacc", "aa", "gg", 2)
13、按照指定的某个字符,为分隔标识,将一个字符串拆分成字符串数组,strings.Split("hello,world,ok", ",")
strs := strings.Split("hello,world,ok", ",")
14、将字符串进行大小写转换,strings.ToLower("dFsdfJNS"),strings.ToUpper("dFsdfJNS")
lower := strings.ToLower("dFsdfJNS") upper := strings.ToUpper("dFsdfJNS")
15、将字符串左右两边的空格去掉,strings.TrimSpace(" welcone to china ")
str := strings.TrimSpace(" welcone to china ")
16、判断字符串是否以指定的字符串开头:strings.HasPrefix("http://www.baidu.com", "http")
b := strings.HasPrefix("http://www.baidu.com", "http")
17、判断字符串是否以指定字符串结束:strings.HasSuffix("http://www.baidu.com", ".com")
b := strings.HasSuffix("http://www.baidu.com", ".com")