Kotlin String - compareTo() Function



The Kotlin string compareTo() function is used to compare two strings lexicographically. It determines the ordering of two strings and returns zero if current object is equal to the specified other object, a negative number if it's less than other, or a positive number if it's greater than other.

Syntax

Following is the syntax of the Kotlin string compareTo() function −

fun compareTo(other: String): Int

Parameters

This function accepts another object as a parameter, which represents a string that needs to be compared with the current string.

Return value

This function returns integer value.

Example 1: Compare String with Other String

Following is the basic example, here how we can use compareTo() to compare current string with other string lexicographically in kotlin −

fun main() {
   val string1 = "Kotlin"
   val string2 = "Kotlin"
   val string3 = "Java"

   // Lexicographical comparison
   println(string1.compareTo(string2)) 
   println(string1.compareTo(string3))
}

Output

Following is the output −

0
1

Example 2: Impact of Whitespace in String

Now, let's look at another example of the CompareTo() function. What if both the strings are equal but the other one has whitespace?

fun main() {
   val string1 = "Kotlin"
   val string2 = "Kotlin "

   // Lexicographical comparison
   println(string1.compareTo(string2)) 
}

Output

Following is the output −

-1

Example 3: Case-Insensitive Comparison

In this following example we use CompareTo() function to perform a case-insensitive comparison −

fun main() {
   val string1 = "Kotlin"
   // Case-insensitive comparison
   println(string1.compareTo("kotlin", ignoreCase = true))
   println(string1.compareTo("kotlin"))
}

Output

Following is the output −

0
-32
kotlin_strings.htm
Advertisements