doumei1908 2013-10-07 17:59
浏览 21
已采纳

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

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

I want to traverse a string and return the character values. How do I, not return the numeric values per each letter, and return the actual characters?

Now I am getting this

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

My desired output would be

 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)
    }   
 }

Thanks,

  • 写回答

3条回答 默认 最新

  • dtcd27183 2013-10-07 18:34
    关注

    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.

    For example,

    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))
        }
    }
    

    Output:

    H
    e
    l
    l
    o
    
    0 72 H
    1 101 e
    2 108 l
    3 108 l
    4 111 o
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么