Kotlin – Check if Strings are Equal ignoring Case

Check if two strings are equal ignoring case in Kotlin

To check if given two strings are equal ignoring the case of characters in the strings in Kotlin, you can use String.equals() function with ignoreCase=true.

Call the equals() function on the first string object, pass the second string and ignoreCase=true as arguments.

str1.equals(str2, ignoreCase = true)

This expression returns a boolean value of true if the two strings are equal when the case of the characters is not considered, or false if not. We can use the above function call as a condition in if-else statement.

When ignoring the case, the characters 'A' and 'a' are equal.

Examples

Check if the strings “apple” and “APPLe” are equal, when the case is ignored

In the following program, we take a two string values in str1 and str2, and check if the string values in these two string variables are equal ignoring the case.

Kotlin Program

fun main() {
    val str1 = "apple"
    val str2 = "APPLe"

    if (str1.equals(str2, ignoreCase = true)) {
        print("Two strings are equal, ignoring the case.")
    } else {
        print("Two strings are not equal, ignoring the case.")
    }
}

Output

Two strings are equal, ignoring the case.

Check if the strings “apple” and “BANAna” are equal, when the case is ignored

In the following program, we take a two string values in str1 and str2, and check if the string values in these two string variables are equal ignoring the case.

We have take the string values such that they are not equal even when their case is ignored. Therefore else-block must execute.

Kotlin Program

fun main() {
    val str1 = "apple"
    val str2 = "BANAna"

    if (str1.equals(str2, ignoreCase = true)) {
        print("Two strings are equal, ignoring the case.")
    } else {
        print("Two strings are not equal, ignoring the case.")
    }
}

Output

Two strings are not equal, ignoring the case.