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

Viewed 6349

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

3 Answers

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
}
Related