snippetgoCritical
How do I compare strings in GoLang?
Viewed 0 times
golanghowcomparestrings
Problem
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)
}Solution
== 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" {
// ...
}Code Snippets
if strings.TrimRight(input, "\n") == "a" {
// ...
}Context
Stack Overflow Q#34383705, score: 169
Revisions (0)
No revisions yet.