方法:首先使用for语句遍历字符串,语法“for i := 0; i < len(字符串变量); i++{}”或“for _, s := range 字符串变量{}”;然后在循环体“{}”里使用“fmt.Printf()”函数逐一输出即可。
本教程操作环境: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语言中字符串怎么逐个取出的知识。速戳>>知识兔学习精品课!