Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation as to why this String comparison results in false?

Tags:

kotlin

Could anyone explain why the following line of code results in false.

The code returns true if the Strings aren't capitalized. Shouldn't ignoring the case mean the result is the same?

System.out.print(
    String("Carthorse".toCharArray().sortedArray())
   .equals(String("Orchestra".toCharArray().sortedArray()),true)
)
like image 566
HakunaMatata Avatar asked Mar 07 '23 03:03

HakunaMatata


1 Answers

The sorting does not ignore cases, here's what you're actually comparing:

//Caehorrst vs. Oacehrrst

Try the following instead:

val s1 = String("Carthorse".toLowerCase().toCharArray().sortedArray())
val s2 = String("Orchestra".toLowerCase().toCharArray().sortedArray())
println("$s1 vs. $s2, equal? ${s1==s2}")
//acehorrst vs. acehorrst, equal? true

Or with a bit more fun:

fun String.sortedCaseIgnore() = 
    String(toLowerCase().toCharArray().sortedArray())
val s1 = "Carthorse".sortedCaseIgnore()
val s2 = "Orchestra".sortedCaseIgnore()

And btw, use println() in favor of System.out.println(), here's its definition (part of Kotlin's standard library, no explicit import required):

public inline fun println(message: Any?) {
    System.out.println(message)
}
like image 61
s1m0nw1 Avatar answered Apr 25 '23 11:04

s1m0nw1