[Golang]中文字符串的编码转换

golang在处理中文时默认的是utf-8编码,当某些情况下遇到GBK编码或需要GBK编码时,就会出现显示乱码的问题。

1. simplifiedchinese 

golang官方有针对中文编码转换的包:golang.org/x/text/encoding/simplifiedchinese 

import "golang.org/x/text/encoding/simplifiedchinese"

func ConvertStr2GBK(str string) string {
    //将utf-8编码的字符串转换为GBK编码
    ret, err := simplifiedchinese.GBK.NewEncoder().String(str)
    return ret   //如果转换失败返回空字符串

    //如果是[]byte格式的字符串,可以使用Bytes方法
    b, err := simplifiedchinese.GBK.NewEncoder().Bytes([]byte(str))
    return string(b)
}

func ConvertGBK2Str(gbkStr string) string {
    //将GBK编码的字符串转换为utf-8编码
    ret, err := simplifiedchinese.GBK.NewDecoder().String(gbkStr)
    return ret //如果转换失败返回空字符串

    //如果是[]byte格式的字符串,可以使用Bytes方法
    b, err := simplifiedchinese.GBK.NewDecoder().Bytes([]byte(gbkStr))
    return string(b)
}

一般情况下,simplifiedchinese.GBK与simplifiedchinese.GB18030可以通用,区别在于字符集不同。


2. mahonia

还可以使用第三方的包:github.com/axgle/mahonia

func Convert2GBK(str string) string {

    return mahonia.NewEncoder("gbk").ConvertString(title)

}


3. 例子

zserge/webview在显示网页窗口时,其title字符串如果包含中文,则在不同平台上要求传递的编码格式不同。
MacOS上直接传递utf-8编码的字符串,windows则需要传递GBK编码的字符串。


import "github.com/zserge/webview"
import "golang.org/x/text/encoding/simplifiedchinese"

title := "微信扫码登录"
if strings.ToLower(runtime.GOOS) == "windows" {
    //如果不转换为GBK编码,则窗口标题显示乱码
    title, _ = simplifiedchinese.GBK.NewEncoder().String(title)
}
webview.Open(title, uri, 400, 600, true)

猜你喜欢

转载自blog.csdn.net/youngwhz1/article/details/89670001
今日推荐