Golang 字符串长度之 len 和 RuneCountInString 的区别和用法

len

Go 的内置函数 len(),可以用来获取切片、字符串、通道(channel)等的长度。

  t1 := "hello world!"
  fmt.Println(len(t1)) // 输出 12

  t2 := "神兽"
  fmt.Println(len(t2)) // 输出 6

len() 函数的返回值的类型为 int,表示字符串的 ASCII 字符个数或字节长度。

  • 输出中第一行的 12 表示 t1 的字符个数为 12。
  • 输出中第二行的 6 表示 t2 的字符格式,也就是 “神兽” 的字符个数是 6,然而根据习惯,“神兽”的字符个数应该是 2。

这里的差异是由于 Go 语言的字符串都以 UTF-8 格式保存,每个中文占用 3 个字节,因此使用 len() 获得两个中文文字对应的 6 个字节。

如果希望按习惯上的字符个数来计算,就需要使用 Go 语言中 UTF-8 包提供的 RuneCountInString() 函数,统计 Uncode 字符数量。

RuneCountInString

计算 UTF-8 的字符个数

fmt.Println(utf8.RuneCountInString("神兽")) // 输出 2
fmt.Println(utf8.RuneCountInString("去吧神兽,fight!")) // 输出 11

总结

  • ASCII 字符串长度使用 len() 函数。
  • Unicode 字符串长度使用 utf8.RuneCountInString() 函数。
posted @ 2022-01-06 09:50  Java-练习生  阅读(35)  评论(0)    收藏  举报