美文网首页
Go语言中遍历字符串的两种方式

Go语言中遍历字符串的两种方式

作者: 码二哥 | 来源:发表于2020-01-26 09:13 被阅读0次

参考:
http://c.biancheng.net/view/37.html

关键词:

记住下面两种方式:

  • 使用下标方式
    • 得到的是ASCII字符
  • 使用for range
    • 得到的是Unicode字符
  • 如何正常输出字符串中的汉字呢?

使用ASCII方式遍历字符

遍历 ASCII 字符使用 for 的数值循环进行遍历,直接取每个字符串的下标获取 ASCII 字符,如下面的例子所示。

theme := "狙击 start"
for i := 0; i < len(theme); i++ {
    fmt.Printf("ascii: %c  %d\n", theme[i], theme[i])
}

程序输出如下:

ascii: ?  231
ascii:     139
ascii:     153
ascii: ?  229
ascii:     135
ascii: ?  187
ascii:    32
ascii: s  115
ascii: t  116
ascii: a  97
ascii: r  114
ascii: t  116

这种模式下取到的汉字“惨不忍睹”。由于没有使用 Unicode,汉字被显示为乱码。

使用Unicode方式遍历字符

同样的内容:

theme := "狙击 start"
for _, s := range theme {
    fmt.Printf("Unicode: %c  %d\n", s, s)
}

程序输出如下:

Unicode: 狙  29401
Unicode: 击  20987
Unicode:    32
Unicode: s  115
Unicode: t  116
Unicode: a  97
Unicode: r  114
Unicode: t  116

可以看到,这次汉字可以正常输出了。

相关文章

网友评论

      本文标题:Go语言中遍历字符串的两种方式

      本文链接:https://www.haomeiwen.com/subject/zkrjthtx.html