将字符串索引为字符

dem*_*mas 6 string unicode go

字符串的元素具有类型字节,可以使用通常的索引操作来访问.

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

"一些"[1] - >"o"

Den*_*ret 10

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

var runes = []rune("someString")
Run Code Online (Sandbox Code Playgroud)

请注意,当您迭代字符串时,您不需要转换.从Effective Go看到这个例子:

for pos, char := range "???" {
    fmt.Printf("character %c starts at byte position %d\n", char, pos)
}
Run Code Online (Sandbox Code Playgroud)

这打印

character ? starts at byte position 0
character ? starts at byte position 3
character ? starts at byte position 6
Run Code Online (Sandbox Code Playgroud)