Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a string alphabetically in Kotlin

Tags:

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.

like image 213
Craig1123 Avatar asked Apr 11 '19 16:04

Craig1123


2 Answers

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.

like image 119
Willi Mentzel Avatar answered Nov 02 '22 13:11

Willi Mentzel


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())
like image 7
Kevin Coppock Avatar answered Nov 02 '22 13:11

Kevin Coppock