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('\n') if(input == "a") { isLetterA = true } else { isLetterA = false } fmt.Println("You entered",input) fmt.Println("Is it the letter a?",isLetterA) }
To check if strings are equal in Go programming, use equal to operator == and provide the two strings as operands to this operator. If both the strings are equal, equal to operator returns true, otherwise the operator returns false.
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 \n , \r , spaces, etc. So as a general rule of thumb, try removing those using functions provided by strings package in golang.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.
==
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\n"
(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, "\n") == "a" { // ... }
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, "\r\n") } else { input = strings.TrimRight(input, "\n") }
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.
This happens because on windows lines end with "\r\n"
which is known as CRLF, but on UNIX lines end with "\n"
which is known as LF and that's why we trim "\n"
on unix based operating systems while we trim "\r\n"
on windows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With