donglan8999 2015-12-20 17:23
浏览 171
已采纳

如何在GoLang中比较字符串?

I am unable to produce a 'true' result when it comes to Go string comparison. I wrote the following to explain the issue and attached a screenshot of the output

// string comparison in Go
package main
import "fmt"
import "bufio"
import "os"

func main() {
    var isLetterA bool 

    fmt.Println("Enter the letter a")
    reader := bufio.NewReader(os.Stdin)
    input, _ := reader.ReadString('
')

    if(input == "a") {
        isLetterA = true
    } else {
        isLetterA = false 
    }

    fmt.Println("You entered",input)
    fmt.Println("Is it the letter a?",isLetterA)

}

example

  • 写回答

3条回答 默认 最新

  • doulidai6316 2015-12-20 17:27
    关注

    == is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString do not contain "a", but "a " (if you look closely, you'll see the extra line break in your example output).

    You can use the strings.TrimRight function to remove trailing whitespaces from your input:

    if strings.TrimRight(input, "
    ") == "a" {
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 python动态规划:N根火柴摆出的最大数字
  • ¥20 (标签-excel)
  • ¥200 求idea10和MyEclipse7.1
  • ¥20 vb6.0截取当前窗体保存为jpg文件
  • ¥20 苹果手机不使用大疆sdk怎么获取遥控器控制信息或如何接入大疆sdk并且成功上架sdk
  • ¥20 woocommerce 注册按键重定向
  • ¥100 求书法图像文字切割代码
  • ¥15 同一个波形探测距离不同的目标,为什么fft之后得到的频谱图会发生移动,不应该时移不改变幅度谱吗(标签-matlab)(相关搜索:matlab仿真)
  • ¥15 Proteus仿真程序只能执行一次
  • ¥15 语音识别websocket报错