在Golang中,要将一个字符串转换为字节数组,你会得到一个包含字符串字节的片断。在Go中,一个字符串实际上是一个只读的字节片。有必要在前面说明,一个字符串可以容纳任意的字节。它不需要持有Unicode文本、UTF-8文本或任何其他预定义的格式。就字符串的内容而言,它正好等同于一个字节片。
Golang字符串到字节数组
在Golang中,要将String转换为Byte数组,可以使用byte()函数。一个字节是一个8位无符号int。byte()函数接受一个字符串作为输入并返回数组。
在Golang中,我们经常使用字节片。 下面是一个Go的例子,展示了如何将一个字符串转换为一个字节数组:
package main
import "fmt"
func main() {
str := "MBB$"
data := []byte(str)
fmt.Println(data)
}
输出
go run hello.go
[77 66 66 36]
在代码中,首先,我们定义了字符串MBB$,然后将该字符串转换为一个字节片。
然后使用fmt.Println()方法来打印字节数组。
Golang bytes.Index()
这里我们在顶部导入 "bytes"包(在导入语句中)。我们调用byte.Index()来定位具有字节值的序列。
请看下面的代码:
// hello.go
package main
import (
"bytes"
"fmt"
)
func main() {
values := []byte("Pug")
// Search for this byte sequence.
result := bytes.Index(values, []byte("g"))
fmt.Println(result)
// This byte sequence is not found.
result = bytes.Index(values, []byte("Dog"))
if result == -1 {
fmt.Println("Dog not found")
}
}
输出
go run hello.go
2
Dog not found
Golang strings.Index()方法,bytes.Index()函数在序列匹配时返回索引。否则,它返回-1。
在第一个例子中,我们发现g与Pug匹配,所以它返回g在Pug中的索引,也就是2,因为索引是从0开始的。
在第二个例子中,我们没有在Pug中找到Dog序列;这就是为什么它返回Dog没有找到。
Golang 复制字符串到字节片中
Golang copy() 是一个内置的方法,可以将字符串复制到一个字节片中。
请看下面的代码:
// hello.go
package main
import "fmt"
func main() {
// Create an empty byte slice of length 4.
values := make([]byte, 4)
// Copy string into bytes.
animal := "pug"
copied := copy(values, animal)
fmt.Println(copied)
fmt.Println(values)
}
输出
go run hello.go
3
[112 117 103 0]
这里我们创建一个空的4元素的字节片。然后我们复制一个三元素的字符串到其中。
本教程就到此为止。