Case insensitive string comparison in Go
36,281
Solution 1
https://golang.org/pkg/strings/#EqualFold is the function you are looking for. It is used like this (example from the linked documentation):
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(strings.EqualFold("Go", "go"))
}
Solution 2
method 1:
func CompareStringsInCrudeWay(stringA, stringB string) (bool, error) { if strings.ToLower(stringA) == strings.ToLower(stringB) { return true, nil } else { return false, nil } }
method 2:
func Compare(stringA, stringB string) bool { for i := 0; i < len(stringA); i++ { if stringA[i] == stringB[i] { continue } if unicode.ToLower(stringA[i]) != unicode.ToLower(stringB[i]) { return false } } return true }
method 3:
func CompareStringsInEfficientWay(stringA, stringB string) (bool, error) { if strings.EqualFold(stringA, stringB) { return true, nil } else { return false, nil } }
method 3 is actually wrapping method 2, and both are efficient. You can check this blog for more explanation.
Related videos on Youtube
Comments
-
user7610 almost 2 years
How do I compare strings in a case insensitive manner?
For example, "Go" and "go" should be considered equal.
-
lunicon over 4 yearsEqualFold not compare :(
-
lunicon over 4 yearsSorting can use strings.ToLower("Go") < strings.ToLower("go")
-
KBN over 3 years> EqualFold not compare @lunicon what do you mean?
-
lunicon over 3 years@KBN, compare operation can say "more, less or equals", EqualFold retrun boolean
-
Vitaly Zdanevich over 2 yearsPlease paste code as code, not as images.