7

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

icza
  • 389,944
  • 63
  • 907
  • 827
Prasanna
  • 101
  • 1
  • 3

3 Answers3

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
  • 2
    Converting 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