rune 相当于 go 的 char
使用 range 遍历 pos,rune 对
使用 utf8.RuneCountInString(s) 获得字符数量
使用 len 获得字节长度, 使用 []byte 获得字节
一般把字节转成 []rune, 更加容易操作
- package main
- import (
- "fmt"
- "unicode/utf8"
- )
- func main() {
- s:="Yes 我爱上百度!"
- fmt.Println(s)
- for _,b:=range []byte(s) {
- fmt.Printf("%X",b)
- }
- fmt.Println()
- for i,ch:=range s{//ch is a rune
- fmt.Printf("(%d %X)",i,ch)
- }
- fmt.Println()
- fmt.Println("Rune 长度",
- 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){
- fmt.Printf("(%d %c)",i,ch)
- }
- fmt.Println()
- }
来源: http://www.bubuko.com/infodetail-2524443.html