在 Unicode 中从控制台读取输入,而不是在 golang 中读取 UTF-8(十六进制)

我正在尝试在控制台中使用 bufio 读取用户输入。文本可以包含一些特殊字符(é、à、♫、╬、...)。


代码如下所示:


reader := bufio.NewReader(os.Stdin)

input, _ := reader.ReadString('\n')

例如,如果我键入“é”,ReadString 会将其读取为“c3 a9”而不是“00e9”。如何读取 Unicode 而不是 UTF-8 的文本输入?我需要将此值用作哈希表键。


谢谢


陪伴而非守候
浏览 197回答 2
2回答

温温酱

Go 字符串在概念上是只读字节数组的只读切片。未指定该字节数组的编码,但字符串常量将是 UTF-8 并且在其他字符串中使用 UTF-8 是推荐的方法。Go 提供了方便的函数来访问 UTF-8 作为 unicode 代码点(或 go-speak 中的符文)。字符串上的范围循环将为您进行 utf8 解码。转换为 []rune 将为您提供 rune 切片,即按顺序排列的 unicode 代码点。这些好东西只适用于 UTF-8 编码的字符串/字节数组。我强烈建议在内部使用 UTF-8。一个例子:package mainimport (&nbsp; "bufio"&nbsp; "fmt"&nbsp; "os")func main() {&nbsp; reader := bufio.NewReader(os.Stdin)&nbsp; input, _ := reader.ReadString('\n')&nbsp; println("non-range loop - bytes")&nbsp; for i := 0; i < len(input); i++ {&nbsp; &nbsp; fmt.Printf("%d %d %[2]x\n", i, input[i])&nbsp; }&nbsp; println("range-loop - runes")&nbsp; for idx, r := range input {&nbsp; &nbsp; fmt.Printf("%d %d %[2]c\n", idx, r)&nbsp; }&nbsp; println("converted to rune slice")&nbsp; rs := []rune(input)&nbsp; fmt.Printf("%#v\n", rs)}输入:X é X&nbsp; &nbsp; non-range loop - bytes&nbsp; &nbsp; 0 88 58&nbsp; &nbsp; 1 32 20&nbsp; &nbsp; 2 195 c3&nbsp; &nbsp; 3 169 a9&nbsp; &nbsp; 4 32 20&nbsp; &nbsp; 5 88 58&nbsp; &nbsp; 6 10 a&nbsp; &nbsp; range-loop - runes&nbsp; &nbsp; 0 88 X&nbsp; &nbsp; 1 32&nbsp; &nbsp; 2 233 é&nbsp; &nbsp; 4 32&nbsp; &nbsp; 5 88 X&nbsp; &nbsp; 6 10&nbsp; &nbsp; converted to rune slice&nbsp; &nbsp; []int32{88, 32, 233, 32, 88, 10}

小怪兽爱吃肉

Unicode 和 utf8 没有可比性。字符串可以是 unicode 和 utf8。通过阅读Go 中的字符串、字节、符文和字符,我学到了很多关于这些的东西。要回答你的问题,您可以使用包中的DecodeRuneInStringunicode/utf8。s := "é"rune, _ := utf8.DecodeRuneInString(s)fmt.Printf("%x", rune)什么DecodeRuneInString(s)是,它返回第一个 utf8 编码字符(符文)s以及该字符宽度(以字节为单位)。因此,如果您想在字符串中获取每个符文的 unicode 代码点,请按照以下步骤操作。这是链接文档中给出的示例,仅稍作修改。str := "Hello, 世界"for len(str) > 0 {&nbsp; &nbsp; r, size := utf8.DecodeRuneInString(str)&nbsp; &nbsp; fmt.Printf("%x %v\n", r, size)&nbsp; &nbsp; str = str[size:]}在操场上试试。或者,正如 Juergen 指出的那样,您可以在字符串上使用范围循环来获取字符串中包含的符文。str := "Hello, 世界"for _, rune := range(str) {&nbsp; &nbsp; fmt.Printf("%x \n", rune)}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go