什么叫字节数组?
在Go语言中,字节数组(byte)是通过一系列整数金额所组成的二维数组。每一个整数金额相匹配一个字符,这一标识符由该整数金额在ASCII时速表中相对应的标识符表明。因而,字节数组可以理解为是通过字符集所组成的二维数组,它能够被适用于各种字符串处理情景。
string 转 byte 的办法
Go语言带来了二种将字符串转换为字节数组的办法:一种是由数据转换完成,另一种是根据标准库里的函数公式完成。
(1)数据转换法
在Go语言中,string是一种不可变类型,它是由一串标识符组成。而byte则是一种可变性种类,它是由一系列整数金额组成。因而,我们通过数据转换将string类型转换为byte种类,即:
str := "hello world"
bytes := []byte(str)
str[]byte(str)bytes
(2)函数公式转换法
[]bytestring
str := "hello world"
bytes := []byte(str)
str2 := string(bytes)
strbytesstring(bytes)str2
字符串数组和字节数组的转变运用
将字符串转换为字节数组是Go语言中一项基本的实际操作,它不仅能用以字符串数组和字节数组的互相转变,还可用于各种各样字符串处理情景。下面我们就来看好多个普遍的使用场景:
(1)字节数组分割
字节数组能够被视为由一些整数金额所组成的编码序列。因而,我们通过赋值字节数组,把它拆分成好几个小二维数组:
str := "hello"
bytes := []byte(str)
chunks := [][]byte{}
chunkSize := 2
for i := 0; i < len(bytes); i = chunkSize {
end := i chunkSize
if end > len(bytes) {
end = len(bytes)
}
chunk := bytes[i:end]
chunks = append(chunks, chunk)
}
fmt.Println(chunks)
strbytesbyteschunks
(2)缩小字符串数组
aaabcc[]byte{3, 97, 1, 98, 2, 99}312
str := "aaabcc"
outBytes := []byte{}
currentChar := str[0]
currentCount := 1
for i := 1; i < len(str); i {
if str[i] == currentChar {
currentCount = 1
} else {
outBytes = append(outBytes, byte(currentCount), byte(currentChar))
currentChar = str[i]
currentCount = 1
}
}
outBytes = append(outBytes, byte(currentCount), byte(currentChar))
fmt.Println(outBytes)
stroutBytesstroutBytes