doushang9172 2012-10-05 05:44
浏览 66
已采纳

如何在Go中遍历UTF-8字符串?

I have a string in Chinese:

x = "你好"

I'd like to loop through it and do something with each character in it, something like:

for i, len := 0, len(x); i < len; i++ {
    foo( x[i] ) // do sth.
}

I found that len(x) would return 6 instead of 2, after Google I found the method RuneCountInString which would return the real length of the string, but I still don't know how to loop to make x[i] get the right character, x[0] == '你' for example..

Thanks

  • 写回答

1条回答 默认 最新

  • dpleylxzx47207117 2012-10-05 05:52
    关注

    Use range.

    x = "你好"
    for _, c := range x {
        // do something with c
    }
    

    If you want random-access, you'll need to use code unit indexes rather than character indexes. Fortunately, there is no good reason to need character indexes, so code unit indexes are fine.

    Most languages have the exact same problem. For example, Java and C# use UTF-16, which is also a variable-length encoding (but some people pretend it isn't).

    See the UTF-8 Manifesto for more information about why Go uses UTF-8.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度