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