In Kotlin, comparing two strings can be achieved in multiple ways. Depending on the nature of the comparison, you can decide to use one approach over another. Here, we’ll explore the most common methods for string comparison in Kotlin:
- Using
==
and!=
Operators: This checks for structural equality. - Using the
equals()
Method: This also checks for structural equality, but with an option to ignore case. - Using
compareTo()
Method: For lexicographical comparison.
1. Using ==
and !=
Operators
In Kotlin, the ==
operator checks for structural equality of two strings, i.e., it checks if the content of the two strings is the same. This is unlike Java, where ==
checks for reference equality.
val str1 = "Hello"
val str2 = "Hello"
val str3 = "World"
println(str1 == str2) // true
println(str1 == str3) // false
2. Using the equals()
Method
The equals()
method is another way to compare the content of two strings. The advantage here is that you can also specify if the comparison should be case-sensitive.
val str1 = "Hello"
val str2 = "HELLO"
println(str1.equals(str2)) // false
println(str1.equals(str2, true)) // true
3. Using compareTo()
Method
The compareTo()
method provides a way to do lexicographical comparison. It returns 0
if the strings are equal, a negative number if the first string comes before the second, and a positive number otherwise. Like equals()
, you can also specify if the comparison should be case-sensitive.
val str1 = "apple"
val str2 = "banana"
val str3 = "apple"
println(str1.compareTo(str2)) // negative value
println(str1.compareTo(str3)) // 0
println(str1.compareTo(str2, true)) // negative value
Example
Here’s a simple program that you can run in any online Kotlin compiler:
fun main() {
val strA = "Kotlin"
val strB = "kOTLIN"
val strC = "Java"
// Using `==` operator
println("Using `==` operator:")
println("strA == strB: ${strA == strB}")
println("strA == strC: ${strA == strC}")
// Using `equals()` method
println("\nUsing `equals()` method:")
println("strA.equals(strB): ${strA.equals(strB)}")
println("strA.equals(strB, true): ${strA.equals(strB, true)}")
// Using `compareTo()` method
println("\nUsing `compareTo()` method:")
println("strA.compareTo(strB): ${strA.compareTo(strB)}")
println("strA.compareTo(strB, true): ${strA.compareTo(strB, true)}")
println("strA.compareTo(strC): ${strA.compareTo(strC)}")
}
Using `==` operator:
strA == strB: false
strA == strC: false
Using `equals()` method:
strA.equals(strB): false
strA.equals(strB, true): true
Using `compareTo()` method:
strA.compareTo(strB): -32
strA.compareTo(strB, true): 0
strA.compareTo(strC): 1