Craig1123
Craig1123

Reputation: 1560

How to sort a string alphabetically in Kotlin

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.

Upvotes: 22

Views: 21528

Answers (2)

Willi Mentzel
Willi Mentzel

Reputation: 29844

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.

Upvotes: 35

Kevin Coppock
Kevin Coppock

Reputation: 134664

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())

Upvotes: 9

Related Questions