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 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置