解释为什么这个String比较结果为false?

Hak*_*ata 4 kotlin

任何人都可以解释为什么以下代码行导致错误.

如果字符串未大写,则代码返回true.不应该忽略的情况意味着结果是一样的吗?

System.out.print(
    String("Carthorse".toCharArray().sortedArray())
   .equals(String("Orchestra".toCharArray().sortedArray()),true)
)
Run Code Online (Sandbox Code Playgroud)

s1m*_*nw1 7

排序不会忽略大小写,这是你实际比较的内容:

//Caehorrst vs. Oacehrrst
Run Code Online (Sandbox Code Playgroud)

请尝试以下方法:

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
Run Code Online (Sandbox Code Playgroud)

或者更多fun:

fun String.sortedCaseIgnore() = 
    String(toLowerCase().toCharArray().sortedArray())
val s1 = "Carthorse".sortedCaseIgnore()
val s2 = "Orchestra".sortedCaseIgnore()
Run Code Online (Sandbox Code Playgroud)

顺便说一句,使用println()赞成System.out.println(),这是它的定义(Kotlin的标准库的一部分,不需要明确的导入):

public inline fun println(message: Any?) {
    System.out.println(message)
}
Run Code Online (Sandbox Code Playgroud)