[Golang早读] 如何获取字符串长度?

2,565 阅读1分钟

在 Go 语言中要想获取字符串长度有四种方法,分别为:使用 bytes.Count() 获取、使用 strings.Count() 获取、使用 len() 获取和使用 utf8.RuneCountInString() 获取。

bytes.Count()

语法:bytes.Count(s []byte, sep []byte)

用途:Count计数s中sep的非重叠实例的数量。如果sep是空片,Count返回 1 + sutf-8编码的代码点的数量

fmt.Println(bytes.Count([]byte("cheese"), []byte("e"))) 
fmt.Println(bytes.Count([]byte("five"), []byte(""))) 
// before & after each rune 
// Output: 
// 3 
// 5

注:bytes.Count()是根据utf8代码点进行计算的,所以一个中文和一个字符的长度是一样的。使用 bytes.Count() 获取字符串长度需要减 1.

strings.Count()

语法:strings.Count(str, substr string)

用途:Count计数s中substr的非重叠实例的数量。如果substr是空字符串,Count返回 1 + sUnicode代码点的数量。

fmt.Println(strings.Count("cheese", "e")) 
fmt.Println(strings.Count("five", "")) 
// before & after each rune 
// Output: 
// 3 
// 5

len()

len()是我们最常用的获得字符串长度的方法。通过len()来获取长度时,中文或特殊字符的长度是3,字母的长度是1。如果我们想避免中文字符造成的影响,可以将字符串转成[]rune

utf8.RuneCountInString()

用途:RuneCountInString类似于RuneCount,但它的输入是一个字符串。

当我们使用 utf8.RuneCountInString() 函数获取字符串长度时,一个中文和一个英文字符的长度都为 1.

Code:
str := "Hello, 世界" 
fmt.Println("bytes =", len(str)) 
fmt.Println("runes =", utf8.RuneCountInString(str))
Output:
bytes = 13
runes = 9

什么是unsafe.Sizeof()

语法:Sizeof(x ArbitraryType) uintptr

用途:只返回数据类型的大小,不管引用数据的大小,例:

var str string = "hello"
var str2 string

fmt.Println(unsafe.SizeOf(str), unsafe.SizeOf(str2))
//output:
//16
//16

string类型不是直接存的数据,而是一个结构体,用指针指向实际数据地址

type StringHeader struct { 
    Data uintptr 
    Len int 
}

在64位系统上uintptr int都是8字节,加起来就16了。