This is a creation in Article, where the information may have evolved or changed.
A few ways to get the length of a string
-Use bytes. COUNT () statistics-use strings. COUNT () Statistics-Converts a string to []rune] and calls the Len function for statistics-using UTF8. Runecountinstring () Statistics
Example :
str:= "Helloword" L1:=len ([]rune (str)) l2:=bytes. Count ([]byte (str), nil)-1) l3:=strings. Count (str, "") -1l4:=utf8. Runecountinstring (str) FMT. Println (L1)
Fmt. PRINTLN (L2)
Fmt. Println (L3)
Fmt. Println (L4)
Print Results: all 9
Second, strings. The Count function and the Bytes.count function
The usage of these two functions is the same, just a function on the string, one acting on the byte
The Count method in strings
Func Count (S, Sep string) int{}
Determines the number of occurrences of the character Sep in the string s, returns 1 if it is not found, and returns the length of the string if it is an empty string ("") +1
Cases:
str:= "HelloWorld" FMT. PRINTLN (Strings. Count (str, "O")) //print o number of occurrences, printing result is 2
Note: In Golang, if Chinese characters appear in the string, the Len function cannot be called directly to count the string character length, because in Go, the string is stored in UTF-8 format, and the Len function is called on the string to get the number of bytes contained in the string.
str:= "HelloWorld"
STR1: = "Hello, World" FMT. Println (Len (STR1))//print Result: 13
Fmt. PRINTLN (len (str)) //Print Result: 9 (if it is a string of plain English characters, you can use it to determine the length of the string)