This Kotlin example shows how to compare two strings using == operator and the compareTo() method to compare string content.
Kotlin Comparing Strings Example
In the example, we compare two strings.
package net.javaguides.kotlin.examples
fun main(args: Array < String > ) {
val s1 = "SourceCodeExamples"
val s2 = "sourcecodeexamples"
if (s1 == s2) {
println("Strings are equal")
} else {
println("Strings are not equal")
}
println("Ignoring case")
val res = s1.compareTo(s2, true)
if (res == 0) {
println("Strings are equal")
} else {
println("Strings are not equal")
}
}
Output:
Strings are not equal
Ignoring case
Strings are equal
The == operator compares structural equality, that is, the content of the two strings:
if (s1 == s2) {
The compareTo() method compares two strings lexicographically, optionally ignoring case:
val res = s1.compareTo(s2, true)
Comments
Post a Comment