回答

收藏

如何通过 Go 中的符文遍历字符串?

技术问答 技术问答 321 人阅读 | 0 人回复 | 2023-09-12

我想要这个:. X0 N7 y: M3 T% x
    / _  e1 S& t" a; }& s# T
  • for i := 0; i 但事实证明,它str具有类型byte( uint8) 而不是rune。
    $ g( o7 A# j/ d+ o4 [+ f
  • 如何通过符文而不是字节遍历字符串?& b& H4 d' h, u2 l4 }% G$ T3 c
  •                                                                * O, M( a( c( N2 N# \7 r. S
  •     解决方案:                                                               
    4 L/ o  l; G. b- |+ A; ]1 t: K# [
  •                                                                 请参阅Effective Go 中的这个例子:[code]for pos,char := range "日本语" {    fmt.Printf("character %c starts at byte position %d\n",char,pos)}
    9 W5 g: _. \8 `7 u' l' w) m* b
这打印:8 ~' {$ j4 W* b" v6 n5 P4 l) a
    character 日 starts at byte position 0character 本 starts at byte position 3character 语 starts at byte position 6
    * Q, F/ w) |( C3 r+ ]% F
通过分析 UTF-8 分解单个 Unicode 代码点。
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则