The Kotlin language allows multiple ways to check whether or not two strings are equal. Some of them are:
In Kotlin, ==
is used to check the structural equality of two objects. It will return true
if both the objects have the same value:
fun main(args : Array<String>) {val str1: String = "Hello"val str2: String = "Hello World"val str3: String = "Hello"println(str1 == str2) // returns falseprintln(str1 == str3) // returns true}
Koltin uses the ===
operator for referential equality. It returns true
if the two variables are pointing to the same object and have the same value.
Whenever we initialize a new String
object using ""
, it is automatically placed in the string pool. Such strings will always reference the same object.
fun main(args : Array<String>) {val str1: String = "Hello"val str2 = String("Hello".toCharArray())println(str1 === str2) // returns falseprintln(str1 == str2) // returns true}
equals()
functionAnother method to compare two strings in Kotlin is to use the equals()
function.
This comparison is case sensitive. For case-insensitive string comparison in Kotlin, pass the second argument as True
.
fun main(args : Array<String>) {val str1: String = "Hello"val str2: String = "Hello World"val str3: String = "Hello"val str4: String = "hello"println(str1.equals(str2)) // returns falseprintln(str1.equals(str3)) // returns trueprintln(str1.equals(str4, true)) // returns true}
CompareTo()
functionKotlin has another method, CompareTo()
, which is used to check the order of two strings.
CompareTo()
returns Int
value instead of Boolean
, as follows:
0
This comparison is case sensitive. For case-insensitive string comparison in Kotlin, pass the second argument as True
.
The syntax is:
fun String.compareTo(str: String,ignoreCase: Boolean = false): Int
fun main(args : Array<String>) {val str1: String = "Hello"val str2: String = "hello"println(str1.compareTo(str2, false)) // returns falseprintln(str1.compareTo(str2, true)) // returns true}