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

前端之家收集整理的这篇文章主要介绍了Go,Golang:访问字符串作为字符值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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
原文链接:https://www.f2er.com/go/187056.html

猜你在找的Go相关文章