在 Golang 中,可以使用标准库中的 string() 函数将字节数组转换成字符串。

示例代码:

package main

import "fmt"

func main() {
    bytes := []byte{'h', 'e', 'l', 'l', 'o'}
    str := string(bytes)
    fmt.Println(str) // 输出:hello
}

如果字节数组中存储的是 UTF-8 编码的字符,也可以使用 string() 函数将其转换成字符串。

示例代码:

package main

import "fmt"

func main() {
    bytes := []byte{0xe4, 0xbd, 0xa0, 0xe5, 0xa5, 0xbd}
    str := string(bytes)
    fmt.Println(str) // 输出:你好
}

注意:

  • string() 函数将字节数组中的字节解释为 UTF-8 编码的字符。
  • 如果字节数组中包含非 UTF-8 编码的字节,则转换结果可能无法预期。

总结:

Golang 提供了 string() 函数,可以方便地将字节数组转换成字符串。无论是 ASCII 字符还是 UTF-8 编码的字符,都可以使用该函数进行转换。

Golang 字节数组转字符串:简单易懂的指南

原文地址: http://www.cveoy.top/t/topic/lXbl 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录