How to sort a string alphabetically in Kotlin

So your issue is that CharArray.sort() returns Unit (as it does an in-place sort of the array). Instead, you can use sorted() which returns a List<Char>, or you could do something like:

str.toCharArray().apply { sort() }

Or if you just want the string back:

fun String.alphabetized() = String(toCharArray().apply { sort() })

Then you can do:

println("hearty".alphabetized())

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

val str = "hearty"
val arr = str.toCharArray()
println(arr.sorted().joinToString("")) // aehrty

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

Tags:

Kotlin