package main import ( "fmt" "unicode/utf8" ) /* rune 相当于go的char 使用range遍历 pos ,rune 对 使用utn8.RuneCountInString 获得字符数量 使用len 获得字节长度 使用[]byte 获得字节 */ func main() { s := "love中国!" //UTF-8 一个字占三个字节 ,英文一字节 fmt.Println(s) for _, b := range []byte(s) { fmt.Printf("%X ", b) } fmt.Println() // 以下把s 对utf8 进行解码,转换成unicode ,之后赋值给 rune for i, ch := range s { // ch is a rune(四字节) fmt.Printf(" (%d %X) ", i, ch) } fmt.Println() fmt.Println(" Rune Count:", utf8.RuneCountInString(s)) bytes := []byte(s) for len(bytes) > 0 { ch, size := utf8.DecodeRune(bytes) bytes = bytes[size:] fmt.Printf("%c ", ch) } fmt.Println() for i, ch := range []rune(s) { // ch is a rune(四字节) fmt.Printf(" (%d %c) ", i, ch) } }