Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

在 Go 語言中正確處理 Unicode 字串

如果說 Go 平常是指去公園散步,那用 Go 處理 Unicode 大概就是不小心踩進雷區。先來看一個簡單問題:「Hello,世界」的長度是多少?

fmt.Println(len("Hello, 世界www.linuxidc.com"))

>>> 13

13?不是 9 嗎?多出的 4 個是怎麼來的?Go 在編譯時把字串當成 byte 序列編碼,不像 Python 2.x 那樣讓你明確區分 ASCII 與解碼。中文字元在 UTF-8 中佔 3 個 byte,普通字元佔 1 個,所以 1*7+3*2=13。對習慣用 len 檢查 ASCII 字串的人來說,這是個大坑:

hello := "Hello, 世界www.linuxidc.com" for i := range hello {
    fmt.Print(string(hello[i]))
}

>>> Hello, äç

「世界」變亂碼了。改用第二種 range 寫法就正常:

hello := "Hello, 世界www.linuxidc.com" for _, c := range hello {
    fmt.Print(string(c))
}

>>> Hello, 世界www.linuxidc.com

但我們不能總是靠它。假設要比較字串中相鄰兩個字元是否相同,直覺寫法:

func CompareChars(word string) { for i, c := range word { if i < len(word)-1 {
            fmt.Print(string(word[i+1]) == string(c), ",")
    }
  }
}
...
CompareChars("hello")
>>> false,false,true,false,

換成中文就全盤皆錯:

CompareChars("你好好好")

>>> false,false,false,false,

因為我們拿「好」跟「好」的第一個 byte(\xE5)在比,永遠不可能相等。

解法是引入 unicode/utf8 套件。它功能不多,但足以解決問題,例如查字串長度:

import ( "fmt" "unicode/utf8" ) ... fmt.Println(utf8.RuneCountInString("Hello, 世界www.linuxidc.com"))

>>> 9

再來升級 CompareChars:

func CompareChars(word string) { s := []byte(word) for utf8.RuneCount(s) > 1 { r, size := utf8.DecodeRune(s) s = s[size:] nextR, size := utf8.DecodeRune(s) fmt.Print(r == nextR, ",") } }
... CompareChars("hello")
>>> false,false,true,false, CompareChars("你好好好")
>>> false,true,true,

終於正常了。

結論:處理字串迴圈時要格外小心 Unicode 的 byte 與 rune 差異,該用 UTF-8 封裝時就別硬用索引,測試也要同時涵蓋中文與 ASCII 兩種輸入。

Copyright © Linux教程網 All Rights Reserved