1、例题
package main import ( "fmt" "unicode/utf8" )
// 统计字符长度 func main() { s := "Yes我爱go&python!" fmt.Println("len(s) =",len(s)) fmt.Printf("%X \n",[]byte(s)) for _,b := range []byte(s) { fmt.Printf("%X ",b) } fmt.Println() // 发现中文占了3个字符 for i,ch := range s { //ch is rune fmt.Printf("[%d %X] ",i,ch) } fmt.Println() // 统计rune长度 fmt.Println("rune count: ",utf8.RuneCountInString(s)) // byte 转 rune bytes := []byte(s) //fmt.Println(len(bytes)) fmt.Println(bytes) for len(bytes) > 0 { ch , size := utf8.DecodeRune(bytes) bytes = bytes[size:] //fmt.Println(bytes) //fmt.Println(size) fmt.Printf("%c ",ch) } fmt.Println() for i,ch := range []rune(s) { fmt.Printf("[%d %c] ",i,ch) } }