字符和符号(rune)
Go有两种字符类型:
byte
是长度为1字节的值,它是uint8
类型的别名rune
是长度为4字节的Unicode码位(Code-Point),它是int32
的别名
byte
和rune
的零值是0。
使用byte遍历字符串
package main
import (
"fmt"
)
func main() {
s := "str"
for i := 0; i < len(s); i++ {
c := s[i]
fmt.Printf("Byte at index %d is '%c' (0x%x)\n", i, c, c)
}
}
👉 点击此处 👈 在编程操场执行上述代码。
使用rune遍历字符串
package main
import (
"fmt"
)
func main() {
s := "中国汉字"
for i, runeChar := range s {
fmt.Printf("Rune at byte position %d is %#U\n", i, runeChar)
}
}
👉 点击此处 👈 在编程操场执行上述代码。
一个字符串本质上是一个字节数组。
当用rune
遍历字符串时,编译器会假定待遍历的是用UTF-8编码的Unicode字符串。
UTF-8是一种变长编码方案,被编码的每个字符的长度可能是1,2,3或4字节。这样遍历时,返回的变量i
表示每个字符起始字节的位置,而不是字符所在串中第几个位置。
最后更新于
这有帮助吗?