dongliang7545 2016-08-31 09:22
浏览 600
已采纳

Golang从符文转换为字符串

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))
}
  • 写回答

2条回答 默认 最新

  • douchen7324 2016-08-31 09:31
    关注

    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 runes of special tokens controlled by the Scanner.Mode bitmask, and it returns special constants form the text/scanner package, not the read rune itself.

    To read a single rune use Scanner.Next() instead:

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

    Output:

    97 a 'a'
    

    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:

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

    So:

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

    Outputs:

    97 a
    

    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)
    ", i, r, r)
    }
    

    Output:

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

    Or you can simply convert a string value to []rune:

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

    There is also utf8.DecodeRuneInString().

    Try the examples on the Go Playground.

    Note:

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

    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.Ident because "a" is a valid Go identifier:

      c := b.Scan()
      if c == scanner.Ident {
          fmt.Println("Identifier:", b.TokenText())
      }
      
      // Output: "Identifier: a"
      
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算