Kotlin – Compare Strings
To compare strings in Kotlin, use String.compareTo() method.
Given two strings str1
and str2
, and if we would like to compare string str1
to string str2
, call compareTo() method on string str1
and pass the string str2
as argument to the method as shown below.
str1.compareTo(str2)
compareTo() method returns
- zero, if str1 equals str2
- negative number if str1 is less than str2 lexicographically
- positive number if str1 is greater than str2 lexicographically
Example 1 – Two Strings are Equal
In this example, we will take two strings in str1 and str2, such that both have same string values. We shall compare them using compareTo() method and observe the result.
Kotlin Program
fun main(args: Array<String>) { val str1 = "abcd" val str2 = "abcd" val result = str1.compareTo(str2) println("Value returned by compareTo() : " + result) if (result == 0) { println("The two strings are equal.") } }
Output
Value returned by compareTo() : 0 The two strings are equal.
Example 2 – String is Less than Other String
In this example, we will take two strings in str1 and str2, such that str1 occurs before str2 in lexicographical order. We shall compare them using compareTo() method and observe the result. compareTo() should return a negative value.
Kotlin Program
fun main(args: Array<String>) { val str1 = "abc" val str2 = "bcd" val result = str1.compareTo(str2) println("Value returned by compareTo() : " + result) if (result < 0) { println("This string str1 is less than the other string str2.") } }
Output
Value returned by compareTo() : -1 This string str1 is less than the other string str2.
Example 3 – String is Greater than Other String
In this example, we will take two strings in str1 and str2, such that str1 occurs after str2 in lexicographical order. We shall compare them using compareTo() method and observe the result. compareTo() should return a positive value.
Kotlin Program
fun main(args: Array<String>) { val str1 = "bcd" val str2 = "abc" val result = str1.compareTo(str2) println("Value returned by compareTo() : " + result) if (result > 0) { println("This string str1 is greater than the other string str2.") } }
Output
Value returned by compareTo() : 1 This string str1 is greater than the other string str2.
Conclusion
In this Kotlin Tutorial, we learned how to compare two strings using String.compareTo() method, with the help of Kotlin example programs.