将字符串索引为字符

The elements of strings have type byte and may be accessed using the
usual indexing operations.

如何将字符串元素作为char?

“some”[1] -> “o”

最佳答案
最简单的解决方案是将其转换为符文数组:

var runes = []rune("someString")

请注意,当您迭代字符串时,您不需要转换.从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

转载注明原文:将字符串索引为字符 - 代码日志