分享
golang实现unicode码和中文之间的转换
borey · · 25278 次点击 · · 开始浏览这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。
将中文转换为unicode码,使用golang中的strconv包中的QuoteToASCII直接进行转换,将unicode码转换为中文就比较麻烦一点,先对unicode编码按\u进行分割,然后使用strconv.ParseInt,将16进制数字转换Int64,在使用fmt.Sprintf将数字转换为字符,最后将其连接在一起,这样就变成了中文字符串了。 参考代码如下:
1 package main 2 3 import ( 4 "fmt" 5 "strconv" 6 "strings" 7 ) 8 9 func main() { 10 sText := "中文" 11 textQuoted := strconv.QuoteToASCII(sText) 12 textUnquoted := textQuoted[1 : len(textQuoted)-1] 13 fmt.Println(textUnquoted) 14 15 sUnicodev := strings.Split(textUnquoted, "\\u") 16 var context string 17 for _, v := range sUnicodev { 18 if len(v) < 1 { 19 continue 20 } 21 temp, err := strconv.ParseInt(v, 16, 32) 22 if err != nil { 23 panic(err) 24 } 25 context += fmt.Sprintf("%c", temp) 26 } 27 fmt.Println(context) 28 }
运行结果:
1 \u4e2d\u6587 2 中文
有疑问加站长微信联系(非本文作者)
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
关注微信25278 次点击
下一篇:go循环
添加一条新回复
(您需要 后才能回复 没有账号 ?)
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码` - 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传
收入到我管理的专栏 新建专栏
将中文转换为unicode码,使用golang中的strconv包中的QuoteToASCII直接进行转换,将unicode码转换为中文就比较麻烦一点,先对unicode编码按\u进行分割,然后使用strconv.ParseInt,将16进制数字转换Int64,在使用fmt.Sprintf将数字转换为字符,最后将其连接在一起,这样就变成了中文字符串了。 参考代码如下:
1 package main 2 3 import ( 4 "fmt" 5 "strconv" 6 "strings" 7 ) 8 9 func main() { 10 sText := "中文" 11 textQuoted := strconv.QuoteToASCII(sText) 12 textUnquoted := textQuoted[1 : len(textQuoted)-1] 13 fmt.Println(textUnquoted) 14 15 sUnicodev := strings.Split(textUnquoted, "\\u") 16 var context string 17 for _, v := range sUnicodev { 18 if len(v) < 1 { 19 continue 20 } 21 temp, err := strconv.ParseInt(v, 16, 32) 22 if err != nil { 23 panic(err) 24 } 25 context += fmt.Sprintf("%c", temp) 26 } 27 fmt.Println(context) 28 }
运行结果:
1 \u4e2d\u6587 2 中文