Golang从符文转换为字符串 [英] Golang converting from rune to string
问题描述
我有以下代码,应该将 rune
转换为 string
并将其打印出来.但是,在打印时,我得到了未定义的字符.我无法找出错误所在:
I have the following code, it is supposed to cast a rune
into a string
and print it. However, I am getting undefined characters when it is printed. I am unable to figure out where the bug is:
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))
}
推荐答案
那是因为您使用了 Scanner.Scan()
读取 rune
,但它还有其他作用. Scanner.Scan()
可用于读取由 Scanner.Mode
代币或 rune
>位掩码,并以 text/scanner
的形式返回特殊常数.包,而不是读取的符文本身.
That's because you used Scanner.Scan()
to read a rune
but it does something else. Scanner.Scan()
can be used to read tokens or rune
s of special tokens controlled by the Scanner.Mode
bitmask, and it returns special constants form the text/scanner
package, not the read rune itself.
要读取单个 rune
,请使用 Scanner.Next()
代替:
To read a single rune
use Scanner.Next()
instead:
c := b.Next()
fmt.Println(c, string(c), strconv.QuoteRune(c))
输出:
97 a 'a'
如果您只想将单个 rune
转换为 string
,请使用简单类型转化. rune
是 int32
的别名,并将整数转换为 string
:
If you just want to convert a single rune
to string
, use a simple type conversion. rune
is alias for int32
, and converting integer numbers to string
:
将有符号或无符号整数值转换为字符串类型会产生一个包含整数的UTF-8表示形式的字符串.
Converting a signed or unsigned integer value to a string type yields a string containing the UTF-8 representation of the integer.
所以:
r := rune('a')
fmt.Println(r, string(r))
输出:
97 a
还可以遍历 string
值的符文,您只需使用 for ... range
构造:
Also to loop over the runes of a string
value, you can simply use the for ... range
construct:
for i, r := range "abc" {
fmt.Printf("%d - %c (%v)\n", i, r, r)
}
输出:
0 - a (97)
1 - b (98)
2 - c (99)
或者您可以简单地将 string
值转换为 [] rune
:
Or you can simply convert a string
value to []rune
:
fmt.Println([]rune("abc")) // Output: [97 98 99]
在转到游乐场上尝试示例.
注意:
您的原始代码(使用 Scanner.Scan()
)如下所示:
Your original code (using Scanner.Scan()
) works like this:
- 您致电了
Scanner.Init()
将模式(b.Mode
)设置为scanner.GoTokens
. -
在输入上调用
Scanner.Scan()
(从"a"
)返回scanner.Ident
,因为"a"
是有效的Go标识符:
- You called
Scanner.Init()
which sets the Mode (b.Mode
) toscanner.GoTokens
. Calling
Scanner.Scan()
on the input (from"a"
) returnsscanner.Ident
because"a"
is a valid Go identifier:
c := b.Scan()
if c == scanner.Ident {
fmt.Println("Identifier:", b.TokenText())
}
// Output: "Identifier: a"
这篇关于Golang从符文转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!