一、獲取字符串長度的幾種方法
-
- 使用 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
二、strings.Count函數和bytes.Count函數
這兩個函數的用法是相同,只是一個作用在字符串上,一個作用在字節上
strings中的Count方法
func Count(s, sep string) int{}
判斷字符sep在字符串s中出現的次數,沒有找到則返回-1,如果為空字符串("")則返回字符串的長度+1
例:
-
str:= "HelloWorld"
-
fmt.Println(strings.Count(str, "o")) //打印 o 出現的次數,打印結果為2
注:在 Golang 中,如果字符串中出現中文字符不能直接調用 len 函數來統計字符串字符長度,這是因為在 Go 中,字符串是以 UTF-8 為格式進行存儲的,在字符串上調用 len 函數,取得的是字符串包含的 byte 的個數。
-
str:= "HelloWorld"
-
-
str1 := "Hello, 世界"
-
fmt.Println( len(str1)) // 打印結果:13
-
fmt.Println( len(str)) //打印結果:9 (如果是純英文字符的字符串,可以使用來判斷字符串的長度)
-