我想说:
for i := 0; i < len(str); i++ {
dosomethingwithrune(str[i]) // takes a rune
}
但事实证明,str[i]
的类型是byte
(uint8
),而不是rune
.
如何按符号而不是按字节迭代字符串?
我想说:
for i := 0; i < len(str); i++ {
dosomethingwithrune(str[i]) // takes a rune
}
但事实证明,str[i]
的类型是byte
(uint8
),而不是rune
.
如何按符号而不是按字节迭代字符串?
请参阅Effective Go中的此示例:
for pos, char := range "日本語" {
fmt.Printf("character %c starts at byte position %d\n", char, pos)
}
这张照片是:
character 日 starts at byte position 0
character 本 starts at byte position 3
character 語 starts at byte position 6
对于字符串,范围为您做了更多的工作,将单个字符串分开 通过解析UTF-8获得Unicode代码点.