1. 程式人生 > >Go 編碼問題的解決方案

Go 編碼問題的解決方案

int col 方法 .com urn ola split cdata IV

1.首先需要mahonia 這個包

1 go get github.com/axgle/mahonia

然後新建一個 func

src 字符串

srcCode 字符串當前編碼

tagCode 要轉換的編碼

func ConvertToString(src string, srcCode string, tagCode string) string {
    srcCoder := mahonia.NewDecoder(srcCode)
    srcResult := srcCoder.ConvertString(src)
    tagCoder := mahonia.NewDecoder(tagCode)
    _, cdata, _ :
= tagCoder.Translate([]byte(srcResult), true) result := string(cdata) return result }

l例子:

調用ConvertToString 方法

1 str := "亂碼的字符串變量"
2 str  = ConvertToString(str, "gbk", "utf-8")
3 fmt.Println(str)

2.unicode 碼和中文之間的轉換

將中文轉換為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 中文

3. 需要導入的包

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

如果golang.org下載不下來,可以去github上下載克隆版,

go get github.com/zieckey/golang.org

然後將golang.org移動到src目錄下即可。

例子: gbk轉utf-8

1 func gbk2utf8(str byte[]) ([]byte, error) {
2 return ioutil.ReadAll(transform.NewReader(bytes.NewReader(str), simplifiedchinese.GBK.NewDecoder()))
3 }

Go 編碼問題的解決方案