Compare Strings in Kotlin

To Compare Strings in Kotlin, following are some of the possible ways :

Using “==” Operator

We shall use==  operator for comparing two Strings in Kotlin. According to the documentation of Equality in Kotlin,  ==  operator is used for Structural Equality.

a==b  is implicitly translated to a?.equals(b) ?: (b === null)  by Kotlin language.

Make sure that the two valuesa  andb  are of type Strings. Else convert them to Strings before comparison.



Using compareTo() extension function

Kotlin provides compareTo() extension function to String.

Syntax of compareTo() function is given below :

other: String is mandatory argument.
ignoreCase is optional.

The function returns integer value.

Return ValueDescription
0The two strings are equal.
negative integerIf the string is less than the other string
positive integerIf the string is greater than the other string



Conclusion :

In this Kotlin Tutorial – Compare Strings in Kotlin, we have learnt to compare two strings using == Operator and CompareTo() String function, with the help of example programs.