本教程操作环境:windows10系统、go 1.11.2、dell g3电脑。
go语言遍历字符串——获取每一个字符串元素
遍历每一个ascii字符
遍历 ascii 字符使用 for 的数值循环进行遍历,直接取每个字符串的下标获取 ascii 字符,如下面的例子所示。
package mainimport "fmt"func main() { theme := "hello " for i := 0; i < len(theme); i++ { fmt.printf("ascii: %c %d\n", theme[i], theme[i]) }}
程序输出如下:
ascii: h 104ascii: e 101ascii: l 108ascii: l 108ascii: o 111ascii: 32ascii: p 112ascii: h 104ascii: p 112ascii: ä 228ascii: ¸ 184ascii: 173ascii: æ 230ascii: 150ascii: 135ascii: ç 231ascii: ½ 189ascii: 145
这种模式下取到的汉字“惨不忍睹”。由于没有使用 unicode,汉字被显示为乱码。
按unicode字符遍历字符串
同样的内容:
package mainimport "fmt"func main() { theme := "hello " for _, s := range theme { fmt.printf("unicode: %c %d\n", s, s) }}
程序输出如下:
unicode: h 104unicode: e 101unicode: l 108unicode: l 108unicode: o 111unicode: 32unicode: p 112unicode: h 104unicode: p 112unicode: 中 20013unicode: 文 25991unicode: 网 32593
可以看到,这次汉字可以正常输出了。
总结
ascii 字符串遍历直接使用下标。
unicode 字符串遍历用 for range。
推荐学习:golang教程
以上就是go语言中字符串怎么逐个取出的详细内容。
