go underlying implementation language string byte array, using UTF-8 encoding, it can not be changed after the initialization
Get string length
First, when all the characters in the string are single-byte characters, using the len function to get the length of the string
package main
import "fmt"
func main() {
var str string
str = "Hello world"
fmt.Printf("The length of \"%s\" is %d. \n", str, len(str))
}
Enter the above program results: The length of "Hello world" is 11.
Second, when a string contains multi-byte characters when there are two ways to obtain the length of the string
1, use standard library utf8 in RuneCountInString function to obtain the length of the string
package main import ( "fmt" "unicode/utf8" ) func main() { str := "Hello, 世界"
fmt.Println("bytes =", len(str)) fmt.Println("runes =", utf8.RuneCountInString(str)) }
Enter the above program results:
bytes = 13
runes = 9
2, to convert the string to rune slices , then len obtaining length function
package main import ( "fmt" ) func main() { str := "Hello, 世界" runes := []rune(str) fmt.Printf("The byte length of \"%s\" a is %d \n", str, len(str)) fmt.Printf("The length of \"%s\" a is %d \n", str, len(runes)) }
The above program output:
The byte length of "Hello, 世界" a is 13
The length of "Hello, 世界" a is 9