golang 字符串統計
阿新 • • 發佈:2018-09-13
instr 行存儲 英文 函數 tr1 世界 light strings str1
golang內建只認utf8
如果傳遞的字符串裏含有漢字什麽的,最好使用 utf8.RuneCountInString() 統計
字符串統計幾種方法:
- 使用 bytes.Count() 統計
- 使用 strings.Count() 統計
- 將字符串轉換為 []rune 後調用 len 函數進行統計
- 使用 utf8.RuneCountInString() 統計
str:="HelloWord" l1:=len([]rune(str)) l2:=bytes.Count([]byte(str),nil)-1) l3:=strings.Count(str,"")-1 l4:=utf8.RuneCountInString(str) fmt.Println(l1) fmt.Println(l2) fmt.Println(l3) fmt.Println(l4) 打印結果:都是 9
註:在 Golang 中,如果字符串中出現中文字符不能直接調用 len 函數來統計字符串字符長度,這是因為在 Go 中,字符串是以 UTF-8 為格式進行存儲的,在字符串上調用 len 函數,取得的是字符串包含的 byte 的個數。
str:="HelloWorld"
str1 := "Hello, 世界" fmt.Println(len(str1)) // 打印結果:13
fmt.Println(len(str)) //打印結果:9 (如果是純英文字符的字符串,可以使用來判斷字符串的長度)
golang 字符串統計