string Golang 从符文转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39245610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:33:21  来源:igfitidea点击:

Golang converting from rune to string

stringparsinggounicoderune

提问by user3551708

I have the following code, it is supposed to cast a runeinto a stringand print it. However, I am getting undefined characters when it is printed. I am unable to figure out where the bug is:

我有以下代码,它应该将 arune转换为 astring并打印它。但是,我在打印时收到未定义的字符。我无法弄清楚错误在哪里:

package main

import (
    "fmt"
    "strconv"
    "strings"
    "text/scanner"
)

func main() {
    var b scanner.Scanner
    const a = `a`
    b.Init(strings.NewReader(a))
    c := b.Scan()
    fmt.Println(strconv.QuoteRune(c))
}

采纳答案by icza

That's because you used Scanner.Scan()to read a runebut it does something else. Scanner.Scan()can be used to read tokensor runes of special tokens controlled by the Scanner.Modebitmask, and it returns special constants form the text/scannerpackage, not the read rune itself.

那是因为你曾经Scanner.Scan()读过 arune但它做了别的事情。Scanner.Scan()可用于读取由位掩码控制的令牌rune特殊令牌Scanner.Mode,它返回text/scanner包中的特殊常量,而不是读取符文本身。

To read a single runeuse Scanner.Next()instead:

改为读取单次rune使用Scanner.Next()

c := b.Next()
fmt.Println(c, string(c), strconv.QuoteRune(c))

Output:

输出:

97 a 'a'

If you just want to convert a single runeto string, use a simple type conversion. runeis alias for int32, and converting integer numbers to string:

如果您只想将单个转换runestring,请使用简单的类型转换rune是 的别名int32,并将整数转换为string

Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.

将有符号或无符号整数值转换为字符串类型会生成一个包含整数的 UTF-8 表示的字符串。

So:

所以:

r := rune('a')
fmt.Println(r, string(r))

Outputs:

输出:

97 a

Also to loop over the runes of a stringvalue, you can simply use the for ... rangeconstruct:

同样要循环遍历string值的符文,您可以简单地使用for ... range构造:

for i, r := range "abc" {
    fmt.Printf("%d - %c (%v)\n", i, r, r)
}

Output:

输出:

0 - a (97)
1 - b (98)
2 - c (99)

Or you can simply convert a stringvalue to []rune:

或者您可以简单地将string值转换为[]rune

fmt.Println([]rune("abc")) // Output: [97 98 99]

There is also utf8.DecodeRuneInString().

还有utf8.DecodeRuneInString()

Try the examples on the Go Playground.

试试Go Playground上的例子。

Note:

笔记:

Your original code (using Scanner.Scan()) works like this:

您的原始代码(使用Scanner.Scan())的工作方式如下:

  1. You called Scanner.Init()which sets the Mode (b.Mode) to scanner.GoTokens.
  2. Calling Scanner.Scan()on the input (from "a") returns scanner.Identbecause "a"is a valid Go identifier:

    c := b.Scan()
    if c == scanner.Ident {
        fmt.Println("Identifier:", b.TokenText())
    }
    
    // Output: "Identifier: a"
    
  1. 您调用Scanner.Init()which 将 Mode ( b.Mode) 设置为scanner.GoTokens
  2. 调用Scanner.Scan()输入 (from "a") 会返回,scanner.Ident因为它"a"是一个有效的 Go 标识符:

    c := b.Scan()
    if c == scanner.Ident {
        fmt.Println("Identifier:", b.TokenText())
    }
    
    // Output: "Identifier: a"
    

回答by MarkJL

I know I'm a bit late to the party but here's a []rune to string function:

我知道我参加聚会有点晚了,但这里有一个 []rune to string 函数:

func runesToString(runes []rune) (outString string) {
    // don't need index so _
    for _, v := range runes {
        outString += string(v)
    }
    return
}

yes, there is a named return but I think it's ok in this case as it reduces the number of lines and the function is only short

是的,有一个命名返回,但我认为在这种情况下可以,因为它减少了行数并且函数很短