douchilian1009 2016-10-16 19:45
浏览 119
已采纳

在Golang的Scanln中使用符文而不是字符串

Below is the code for reading the input from console

var message string
fmt.Scanln(&message)

But I wanted to try same with rune, which is unicode of byte

var input []rune
fmt.Scanln(input)

As per my C/C++ knowledge, where an array's reference can be passed through its name , I thought it would work in case of rune

But surprisingly the program passes Scanln in case of rune without even taking console input

What is that am doing wrong? Or it cannot be done ? Or it requires type casting to string ?

  • 写回答

1条回答 默认 最新

  • dpzzkfb1244 2016-10-16 20:26
    关注

    What you have is a slice not an array, they're different in Go

    When you read each character from a string you will get a rune, for example:

    for _, rune := range input { ... }
    // or
    input[0] // it returns a rune
    

    Now if you want to use index or more unicode manipulation you should keep in mind that each rune has a length and that lenght affects the length of the string too, see this example to better understanding, for example you see 3 characters in the string, but the lenght is 5:

    package main
    
    import (
        "fmt"
        "unicode/utf8"
    )
    
    func main() {
    
        input := "a界c"
    
        fmt.Println(len(input))
    
        for index, rune := range input {
            fmt.Println(index, utf8.RuneLen(rune), string(rune))    
        }
    
        fmt.Println(input[1:4]) // we know that the unicode character '界'
                                // starts in index 1 and ends in index 3
    }
    

    run it here: https://play.golang.org/p/xvmH1laevS

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?
  • ¥15 matlab(相关搜索:紧聚焦)