golang實現unicode碼和中文之間的轉換

將中文轉換爲unicode碼,使用golang中的strconv包中的QuoteToASCII直接進行轉換,將unicode碼轉換爲中文就比較麻煩一點,先對unicode編碼按\u進行分割,而後使用strconv.ParseInt,將16進制數字轉換Int64,在使用fmt.Sprintf將數字轉換爲字符,最後將其鏈接在一塊兒,這樣就變成了中文字符串了。 參考代碼以下:golang

package main

import (
	"fmt"
	"strconv"
	"strings"
)

func main() {
	sText := "中文"
	textQuoted := strconv.QuoteToASCII(sText)
	textUnquoted := textQuoted[1 : len(textQuoted)-1]
	fmt.Println(textUnquoted)

	sUnicodev := strings.Split(textUnquoted, "\\u")
	var context string
	for _, v := range sUnicodev {
		if len(v) < 1 {
			continue
		}
		temp, err := strconv.ParseInt(v, 16, 32)
		if err != nil {
			panic(err)
		}
		context += fmt.Sprintf("%c", temp)
	}
	fmt.Println(context)
}

運行結果:編碼

\u4e2d\u6587
中文
相關文章
相關標籤/搜索