加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

Go,Golang:访问字符串作为字符值

发布时间:2020-12-16 19:20:00 所属栏目:大数据 来源:网络整理
导读: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 i
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)
    }   
 }

谢谢,

07000

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读