How to compare two strings with case insensitivity?
For example: Both "a" == "a"
and "a" == "A"
must return true
.
The EqualFold function in Golang is used to check if two strings are equal. The comparison is not case-sensitive. Note: Here, the strings are interpreted as UTF-8 strings, and all comparisons are done under Unicode case-folding, a more generalized version of case insensitive comparisons.
operators differs from string comparison using the String. CompareTo and Compare(String, String) methods. They all perform a case-sensitive comparison.
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.
There is a strings.EqualFold()
function which performs case insensitive string comparison.
For example:
fmt.Println(strings.EqualFold("aa", "Aa"))
fmt.Println(strings.EqualFold("aa", "AA"))
fmt.Println(strings.EqualFold("aa", "Ab"))
Output (try it on the Go Playground):
true
true
false
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