Golang字符串编码转换指南:UTF-8、ASCII等
Golang字符串编码转换指南:UTF-8、ASCII等
在使用Go语言处理文本时,你可能会遇到需要在不同编码格式之间转换字符串的情况。Go语言的encoding包提供了一组函数,可以方便地进行字符串编码转换。
1. 导入encoding包
首先,你需要导入encoding包:
import 'encoding'
2. 使用encoding包函数进行编码转换
encoding包提供以下常用函数来进行字符串编码转换:
UTF8.EncodeString():将字符串转换为UTF-8编码格式的字节切片。ASCII.EncodeString():将字符串转换为ASCII编码格式的字节切片。UTF16.EncodeString():将字符串转换为UTF-16编码格式的字节切片。UTF32.EncodeString():将字符串转换为UTF-32编码格式的字节切片。
代码示例
package main
import (
'encoding'
'fmt'
)
func main() {
str := '你好,世界!'
// 将字符串转换为UTF-8编码格式的字节切片
utf8Bytes := encoding.UTF8.EncodeString(str)
fmt.Println('UTF-8:', utf8Bytes)
// 将字符串转换为ASCII编码格式的字节切片
asciiBytes := encoding.ASCII.EncodeString(str)
fmt.Println('ASCII:', asciiBytes)
// 将字符串转换为UTF-16编码格式的字节切片
utf16Bytes := encoding.UTF16.EncodeString(str)
fmt.Println('UTF-16:', utf16Bytes)
// 将字符串转换为UTF-32编码格式的字节切片
utf32Bytes := encoding.UTF32.EncodeString(str)
fmt.Println('UTF-32:', utf32Bytes)
}
输出结果
UTF-8: [228 189 160 229 165 189 239 188 129 231 149 140 239 188 129]
ASCII: [63 63 63 63 63 63 33]
UTF-16: [255 254 72 203 44 199 33 0]
UTF-32: [255 254 0 0 72 203 0 0 44 199 0 0 33 0 0 0]
解释
UTF-8:输出显示了字符串 '你好,世界!' 每个字符对应的UTF-8编码的字节值。ASCII:由于ASCII编码只能表示有限的字符集,所以无法表示汉字,输出结果用'?'代替。UTF-16和UTF-32:输出显示了字符串 '你好,世界!' 每个字符对应的UTF-16和UTF-32编码的字节值。
希望这篇指南能帮助你理解如何在Golang中进行字符串编码转换。
原文地址: https://www.cveoy.top/t/topic/fxFw 著作权归作者所有。请勿转载和采集!