如何在Kotlin中按字母顺序对字符串进行排序

Cra*_*123 4 kotlin

我想将字符串“ hearty”重新排序为字母顺序:“ aehrty”

我试过了:

val str = "hearty"
val arr = str.toCharArray()
println(arr.sort())
Run Code Online (Sandbox Code Playgroud)

这将引发错误。我还尝试了的.split("")方法.sort()。这也会引发错误。研究此事无济于事。

Wil*_*zel 7

You need to use sorted() and after that joinToString, to turn the array back to a String:

val str = "hearty"
val arr = str.toCharArray()
println(arr.sorted().joinToString("")) // aehrty
Run Code Online (Sandbox Code Playgroud)

Note: sort() will mutate the array it is invoked on, sorted() will return a new sorted array leaving the original untouched.


kco*_*ock 5

所以你的问题是CharArray.sort()返回Unit(因为它对数组进行了就地排序)。相反,您可以使用sorted()which 返回 a List<Char>,或者您可以执行以下操作:

str.toCharArray().apply { sort() }
Run Code Online (Sandbox Code Playgroud)

或者,如果您只想返回字符串:

fun String.alphabetized() = String(toCharArray().apply { sort() })
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

println("hearty".alphabetized())
Run Code Online (Sandbox Code Playgroud)