In this tutorial, you shall learn how to compare given two strings in Kotlin, using String.compareTo() function, with examples.

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

Examples

ADVERTISEMENT

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.

2. First string is less than the second 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.

3. First string is greater than the second 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.