go语言中len()函数可以获取 数组、数组切片,以及ASCII型字符串(如不含汉字)的长度。
1)ASCII 字符串长度使用 len() 函数。
2)Unicode 字符串长度使用 utf8.RuneCountInString() 函数
3)使用 bytes.Count() 统计
4)使用 strings.Count() 统计
其中,strings.Count函数和bytes.Count函数,这两个函数的用法是相同,只是一个作用在字符串上,一个作用在字节上。
例1:
fmt.Println(utf8.RuneCountInString(“忍者”))
fmt.Println(utf8.RuneCountInString(“龙忍出鞘,fight!”))
程序输出如下:
2
11
例2:
str:=”HelloWord”
l1:=len([]rune(str))
l2:=bytes.Count([]byte(str),nil)-1)
l3:=strings.Count(str,”“)-1
l4:=utf8.RuneCountInString(str)
fmt.Println(l1)
fmt.Println(l2)
fmt.Println(l3)
fmt.Println(l4)
打印结果:都是 9