Kotlin String.compareTo()

Kotlin String.compareTo() Tutorial

The String.compareTo() function in Kotlin is used to compare two strings lexicographically. It returns an integer that represents the difference between the two strings.

This tutorial will explore the syntax of the String.compareTo() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the String.compareTo() function is as follows:

fun String.compareTo(other: String): Int

where

ParameterDescription
otherAnother string value.
Parameters of String.compareTo() function

The compareTo() function returns:

Return ValueDescription
< 0The string is lexicographically less than the other string.
0The strings are lexicographically equal.
> 0The string is lexicographically greater than the other string.
Return values of String.compareTo() function

Examples for String compareTo() function

In these examples, we’ll use compareTo() to compare two strings lexicographically.

1. Comparing Strings

In this example, we take two strings in string1 and string2, and compare the first string to the second string using String.compareTo() function.

Kotlin Program

fun main() {
    val string1 = "apple"
    val string2 = "banana"

    // Using compareTo() to compare two strings
    val result = string1.compareTo(string2)

    // Printing the original strings and the result
    println("String 1: $string1")
    println("String 2: $string2")
    println("Comparison Result: $result")

    if (result > 0) {
        println("\"$string1\" is greater than \"$string2\".")
    } else if (result < 0) {
        println("\"$string1\" is less than \"$string2\".")
    } else {
        println("The two strings are equal.")
    }
}

Output

String 1: apple
String 2: banana
Comparison Result: -1
"apple" is less than "banana".

2. Handling Equal Strings

In this example, we shall take same string value in the strings string1 and string2, and run the program.

Kotlin Program

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

    // Using compareTo() to compare two strings
    val result = string1.compareTo(string2)

    // Printing the original strings and the result
    println("String 1: $string1")
    println("String 2: $string2")
    println("Comparison Result: $result")

    if (result > 0) {
        println("\"$string1\" is greater than \"$string2\".")
    } else if (result < 0) {
        println("\"$string1\" is less than \"$string2\".")
    } else {
        println("The two strings are equal.")
    }
}

Output

String 1: apple
String 2: apple
Comparison Result: 0
The two strings are equal.

Summary

In this tutorial, we’ve covered the compareTo() function in Kotlin strings, its syntax, and how to use it to compare two strings lexicographically. Understanding the return values helps in determining whether one string is less than, equal to, or greater than another.