简体   繁体   English

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

[英]How to access string as character value

http://play.golang.org/p/ZsALO8oF3W 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, 谢谢,

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. 对于字符串值,“range”子句迭代从字节索引0开始的字符串中的Unicode代码点。在连续迭代中,索引值将是连续UTF-8编码的代码点的第一个字节的索引。字符串和rune类型的第二个值将是相应代码点的值。 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. 如果迭代遇到无效的UTF-8序列,则第二个值将是0xFFFD,即Unicode替换字符,下一次迭代将在字符串中前进一个字节。

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

package main Use Printf to indicate you want to print characters. package main使用Printf表示您要打印字符。

import "fmt"

func main() {

        str := "Hello"
        for i, elem := range str {
                fmt.Printf("%d %c %c\n", i, str[i], elem)
        }

}

The way you are iterating over the characters in the string is workable (although str[i] and elem are the duplicative of each other). 迭代字符串中字符的方式是可行的(尽管str [i]和elem是彼此的重复)。 You have the right data. 您拥有正确的数据。

In order to get it to display correctly, you just need to output with the right formatting (ie interpreted as a unicode character rather than an int). 为了使其正确显示,您只需要使用正确的格式输出(即解释为unicode字符而不是int)。

Change: 更改:

fmt.Println(i, str[i], elem)

to: 至:

fmt.Printf("%d %c %c\n", i, str[i], elem)

%c is the character represented by the corresponding Unicode code point per the Printf doc: http://golang.org/pkg/fmt/ %c是每个Printf文档对应的Unicode代码点表示的字符http//golang.org/pkg/fmt/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM