如何在Go中用符文遍历字符串? [英] How can I iterate over a string by runes in Go?
本文介绍了如何在Go中用符文遍历字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要这个:
for i := 0; i < len(str); i++ {
dosomethingwithrune(str[i]) // takes a rune
}
但是事实证明, str [i]
的类型是 byte
( uint8
),而不是 rune
.
But it turns out that str[i]
has type byte
(uint8
) rather than rune
.
如何通过符文而不是字节遍历字符串?
How can I iterate over the string by runes rather than bytes?
推荐答案
请参见有效的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代码.
For strings, the range does more work for you, breaking out individual Unicode code points by parsing the UTF-8.
这篇关于如何在Go中用符文遍历字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文