How to compare two strings with case insensitivity?
For example: Both "a" == "a" and "a" == "A" must return true.
            Asked
            
        
        
            Active
            
        
            Viewed 7,456 times
        
    7
            
            
        - 
                    3Convert them both to lower case, then compare. – zerkms May 17 '17 at 23:48
- 
                    what's the meaning of asking a question then answering it in less than 6 min ? – Chiheb Nexus May 17 '17 at 23:57
- 
                    Must "ß" == "SS" also? – RedGrittyBrick May 18 '17 at 10:27
- 
                    Possible duplicate of [Case insensitive string search in golang](http://stackoverflow.com/questions/24836044/case-insensitive-string-search-in-golang) – WiredPrairie May 18 '17 at 10:34
3 Answers
27
            
            
        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
 
    
    
        icza
        
- 389,944
- 63
- 907
- 827
-1
            
            
        Found the answer. Convert both strings to either lowercase or upper case and compare.
import "strings"
strings.ToUpper(str1) == strings.ToUpper(str2)
 
    
    
        Prasanna
        
- 101
- 1
- 3
- 
                    2Converting strings to lowercase or uppercase only gives an approximately correct result - Unicode isn't this simple. Research the "Turkish i" problem for a starting point on diving down the rabbithole. – Bevan May 01 '20 at 04:58
-2
            
            
        strings.EqualFold() is not compare, some times you need sign of compare
func compareNoCase(i, j string) int {
    is, js := []rune(i), []rune(j)
    il, jl := len(is), len(js)
  ml := il
    if ml > jl {
        ml = jl
    }
    for n := 0; n < ml; n++ {
        ir, jr := unicode.ToLower(is[n]), unicode.ToLower(js[n])
        if ir < jr {
            return -1
        } else if ir > jr {
            return 1
        }
    }
    if il < jl {
        return -1
    }
    if il > jl {
        return 1
    }
    return 0
}
func equalsNoCase(i, j string) bool {
    return compareNoCase(i, j) == 0
}
 
    
    
        lunicon
        
- 1,690
- 1
- 15
- 26