I want to reorder the string "hearty" to be in alphabetical order: "aehrty"
I've tried:
val str = "hearty"
val arr = str.toCharArray()
println(arr.sort())
This throws an error. I've also tried the .split("") method with the .sort(). That also throws an error.
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.
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())
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