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)
)
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With