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" {
        // ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • duanlu6114 2018-06-18 10:36
    关注

    For the Platform Independent Users or Windows users, what you can do is:

    import runtime:

    import (
        "runtime"
        "strings"
    )
    

    and then trim the string like this:

    if runtime.GOOS == "windows" {
      input = strings.TrimRight(input, "
    ")
    } else {
      input = strings.TrimRight(input, "
    ")
    }
    

    now you can compare it like that:

    if strings.Compare(input, "a") == 0 {
      //....yourCode
    }
    

    This is a better approach when you're making use of STDIN on multiple platforms.

    Explanation

    This happens because on windows lines end with " " which is known as CRLF, but on UNIX lines end with " " which is known as LF and that's why we trim " " on unix based operating systems while we trim " " on windows.

    评论
  • doubi3929 2019-06-03 06:34
    关注

    The content inside strings in Golang can be compared using == operator. If the results are not as expected there may be some hidden characters like , , spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.

    For Instance, spaces can be removed using strings.TrimSpace function. You can also define a custom function to remove any character you need. strings.TrimFunc function can give you more power.

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 powerbulider 导入excel文件,显示不完整
  • ¥20 #关于multisim绘图遇到的问题
  • ¥15 用keil调试程序保证结果进行led相关闪烁
  • ¥15 paddle训练自己的数据loss降不下去
  • ¥20 用matlab的pdetool解决以下三个问题
  • ¥15 单个福来轮的平衡与侧向滑动是如何做到的?
  • ¥15 嵌入式Linux固件,能直接告诉我crc32校验的区域在哪不,内核的校验我已经找到了,uboot没有
  • ¥20 h3c静态路要求有详细过程
  • ¥15 调制识别中输入为时频图,星座图,眼图等
  • ¥15 数据结构C++的循环、随机数问题