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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?