Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two string values in Go in a case insensitive manner?

How to compare two strings with case insensitivity? For example: Both "a" == "a" and "a" == "A" must return true.

like image 212
Prasanna Avatar asked May 17 '17 23:05

Prasanna


People also ask

How do you compare string case-insensitive in Golang?

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.

Is comparing strings case-sensitive?

operators differs from string comparison using the String. CompareTo and Compare(String, String) methods. They all perform a case-sensitive comparison.

Can we use == operator to compare two strings?

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.


1 Answers

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
like image 91
icza Avatar answered Nov 15 '22 06:11

icza