小编典典

如何通过 Go 中的符文遍历字符串?

go

我想要这个:

for i := 0; i < len(str); i++ {
    dosomethingwithrune(str[i]) // takes a rune
}

但事实证明,它str[i]具有类型byte( uint8) 而不是rune

如何通过符文而不是字节遍历字符串?


阅读 180

收藏
2021-12-17

共1个答案

小编典典

请参阅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 代码点。

2021-12-17