Unicode是为了解决传统的字符编码方案的局限而产生的,它为每种语言中的每个字符设定了统一并且唯一的二进制编码,以满足跨语言、跨平台进行文本转换、处理的要求。
在实际应用有很多需要中文和unicode转换的场景,这里主要介绍通过golang实现中文和unicode互相转换。
这一步比较简单
示例
sText := "hello 你好"
textQuoted := strconv.QuoteToASCII(sText)
textUnquoted := textQuoted[1 : len(textQuoted)-1]
fmt.Println(textUnquoted)
网上有些例子,通过 u 分隔来实现,这种方式存在局限性。比如字符里面含有非中文字符,就会出现问题。
正确转换示例
package main
import (
"fmt"
"strconv"
"strings"
)
func zhToUnicode(raw []byte) ([]byte, error) {
str, err := strconv.Unquote(strings.Replace(strconv.Quote(string(raw)), `\\u`, `\u`, -1))
if err != nil {
return nil, err
}
return []byte(str), nil
}
func main() {
sText := "hello 你好"
textQuoted := strconv.QuoteToASCII(sText)
textUnquoted := textQuoted[1 : len(textQuoted)-1]
fmt.Println(textUnquoted)
v, _ := zhToUnicode([]byte(textUnquoted))
fmt.Println(string(v))
}
strconv.Quote(s string)string
-> 返回字符串在go语法下的双引号字面值表示,控制字符和不可打印字符会进行转义(t,n等)strconv.Unquote(s string)(t string,err error)
-> 函数假设s是一个半引号、双引号、反引号包围的go语法字符串,解析它并返回它表示的值。(如果是单引号括起来的,函数会认为s是go字符字面值,返回一个单字符的字符串)扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有