Compare two strings for equality in Kotlin
This article explores different ways to compare two strings for equality in Kotlin.
1. Equal-to operator (==) operation
In Kotlin, the structural equality is checked by the == operator and its negated counterpart !=. The expression a == b is translated to a?.equals(b) ?: (b === null).
|
1 2 3 4 5 6 |
fun main() { val s1 = "ABCD" val s2 = "ABCD" println(s1 === s2) // Evaluates to true } |
Note that === should not be used for string equality as it will check for referential equality, i.e., a === b evaluates to true if and only if a and b point to the same object.
2. Using equals() function
Alternatively, you can use the equals() function, which compares the actual contents of a string with another string and returns true if and only if they are equal. Here is an example for matching the two strings using the equals() function.
|
1 2 3 4 5 6 |
fun main() { val s1 = "ABCD" val s2 = "ABCD" println(s1 != null && s1.equals(s2)) // Evaluates to true } |
To perform a comparison with case ignored, pass true as a second parameter to the equals() function.
|
1 2 3 4 5 6 |
fun main() { val s1 = "ABCD" val s2 = "abcd" println(s1 != null && s1.equals(s2, true)) // Evaluates to true } |
3. Using compareTo() function
The compareTo() function compares two strings lexicographically, optionally ignoring case. It returns 0 if the string is equal to the argument. Otherwise, it returns the difference between the two character values present at the first non-matching index. The following code example demonstrates the invocation of the compareTo() function:
|
1 2 3 4 5 6 |
fun main() { val s1 = "ABCD" val s2 = "ABCD" println(s1 != null && s1.compareTo(s2) == 0) // Evaluates to true } |
That’s all about comparing two strings for equality in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)