Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何在Go中通过符文迭代字符串?_String_Loops_Go_Rune - Fatal编程技术网

String 如何在Go中通过符文迭代字符串?

String 如何在Go中通过符文迭代字符串?,string,loops,go,rune,String,Loops,Go,Rune,我想说: for i := 0; i < len(str); i++ { dosomethingwithrune(str[i]) // takes a rune } i:=0的;i

我想说:

for i := 0; i < len(str); i++ {
    dosomethingwithrune(str[i]) // takes a rune
}
i:=0的
;i
但事实证明,
str[i]
的类型是
byte
uint8
),而不是
rune

如何通过符文而不是字节来迭代字符串?

请参见以下示例:

这张照片是:

character 日 starts at byte position 0
character 本 starts at byte position 3
character 語 starts at byte position 6
对于字符串,该范围为您做更多的工作,打破了个人 Unicode代码点通过解析UTF-8实现

例如:

package main

import "fmt"

func main() {
        for i, rune := range "Hello, 世界" {
                fmt.Printf("%d: %c\n", i, rune)
        }
}


输出:

0: H
1: e
2: l
3: l
4: o
5: ,
6:  
7: 世
10: 界

为了反映在中给出的示例,Go允许您轻松地将字符串转换为一段符文,然后迭代,就像您最初希望的那样:

runes := []rune("Hello, 世界")
for i := 0; i < len(runes) ; i++ {
    fmt.Printf("Rune %v is '%c'\n", i, runes[i])
}
请注意,由于
rune
类型是
int32
的别名,我们必须在
Printf
语句中使用
%c
而不是通常的
%v
,否则我们将看到Unicode码点的整数表示(请参阅)

runes := []rune("Hello, 世界")
for i := 0; i < len(runes) ; i++ {
    fmt.Printf("Rune %v is '%c'\n", i, runes[i])
}
Rune 0 is 'H'
Rune 1 is 'e'
Rune 2 is 'l'
Rune 3 is 'l'
Rune 4 is 'o'
Rune 5 is ','
Rune 6 is ' '
Rune 7 is '世'
Rune 8 is '界'