gpt4 book ai didi

go - 如何将字符串作为字符值访问

转载 作者:IT老高 更新时间:2023-10-28 13:02:29 26 4
gpt4 key购买 nike

http://play.golang.org/p/ZsALO8oF3W

我想遍历一个字符串并返回字符值。如何不返回每个字母的数值,而是返回实际字符​​?

现在我得到了这个

 0 72 72
1 101 101
2 108 108
3 108 108
4 111 111

我想要的输出是

 0 h h
1 e e
2 l l
3 l l
4 o o

package main

import "fmt"

func main() {

str := "Hello"
for i, elem := range str {
fmt.Println(i, str[i], elem)
}

for elem := range str {
fmt.Println(elem)
}
}

谢谢,

最佳答案

For statements

For a string value, the "range" clause iterates over the Unicode code points in the string starting at byte index 0. On successive iterations, the index value will be the index of the first byte of successive UTF-8-encoded code points in the string, and the second value, of type rune, will be the value of the corresponding code point. If the iteration encounters an invalid UTF-8 sequence, the second value will be 0xFFFD, the Unicode replacement character, and the next iteration will advance a single byte in the string.

例如,

package main

import "fmt"

func main() {
str := "Hello"
for _, r := range str {
c := string(r)
fmt.Println(c)
}
fmt.Println()
for i, r := range str {
fmt.Println(i, r, string(r))
}
}

输出:

H
e
l
l
o

0 72 H
1 101 e
2 108 l
3 108 l
4 111 o

关于go - 如何将字符串作为字符值访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19231506/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com