How to compare two strings in Kotlin

The Kotlin language allows multiple ways to check whether or not two strings are equal. Some of them are:

1. Using comparision operators

In Kotlin, == is used to check the structural equality of two objects. It will return true if both the objects have the same value:

fun main(args : Array<String>) {
val str1: String = "Hello"
val str2: String = "Hello World"
val str3: String = "Hello"
println(str1 == str2) // returns false
println(str1 == str3) // returns true
}

Koltin uses the === operator for referential equality. It returns true if the two variables are pointing to the same object and have the same value.

Whenever we initialize a new String object using "", it is automatically placed in the string pool. Such strings will always reference the same object.

fun main(args : Array<String>) {
val str1: String = "Hello"
val str2 = String("Hello".toCharArray())
println(str1 === str2) // returns false
println(str1 == str2) // returns true
}

2. Using equals() function

Another method to compare two strings in Kotlin is to use the equals() function.

This comparison is case sensitive. For case-insensitive string comparison in Kotlin, pass the second argument as True.

fun main(args : Array<String>) {
val str1: String = "Hello"
val str2: String = "Hello World"
val str3: String = "Hello"
val str4: String = "hello"
println(str1.equals(str2)) // returns false
println(str1.equals(str3)) // returns true
println(str1.equals(str4, true)) // returns true
}

3. Using CompareTo() function

Kotlin has another method, CompareTo(), which is used to check the order of two strings.

CompareTo() returns Int value instead of Boolean, as follows:

  1. If two strings are equal, it returns 0
  2. If the string is less than the other string, it returns a negative number
  3. If the string is greater than the other string, it returns a positive number

This comparison is case sensitive. For case-insensitive string comparison in Kotlin, pass the second argument as True.

The syntax is:

fun String.compareTo(
str: String,
ignoreCase: Boolean = false
): Int
fun main(args : Array<String>) {
val str1: String = "Hello"
val str2: String = "hello"
println(str1.compareTo(str2, false)) // returns false
println(str1.compareTo(str2, true)) // returns true
}

Free Resources