Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why kotlin == operator returns false for strings that look exactly the same?

One string comes from a file, the other one is initialized with double quotes.

The strings are identical when I inspect them during debugging and when printed out, yet the == operator and equals method both return false when comparing the strings.

like image 869
KalAnd Avatar asked Oct 15 '25 08:10

KalAnd


1 Answers

I started comparing the strings character by character. This function returns the first position where the strings differ, or -1 if they are the same.

private fun characterCompare(lhs: String, rhs: String): Int {
    var i = 0
    while (i < lhs.length && i < rhs.length) {
        val lchar = lhs[i]
        val rchar = rhs[i]

        if (lchar != rchar) {
            return i // I set a breakpoint here to take a look at the values
        }
        i++
    }
    return if (i < lhs.length || i < rhs.length) i else -1
}

...and in my particular case, the problem was that the string that came from the file, contained an UTF8 byte order mark (BOM) at the beginning, which never showed up when the string was displayed.

This funcion removes the BOM if it is present:

private const val UTF8_BOM = "\uFEFF"
private fun removeUTF8BOM(str: String): String {
    return if (str.startsWith(UTF8_BOM)) {
        str.substring(1)
    } else {
        str
    }
}
like image 66
KalAnd Avatar answered Oct 16 '25 22:10

KalAnd