Kotlin – Sort Characters in String

Sort characters in string in Kotlin

To sort characters in a given string in Kotlin, you can convert the string into a character array, sort the items in the character array, and create a string with the sorted character array. The string created in the last step is the desired string with sorted characters from the original string.

Step 1

Convert given string str to character array.

val charArray = str.toCharArray()

Step 2

Sort characters in the array in ascending order.

charArray.sort()

If you would like to sort the characters in descending order, you may use the following function.

charArray.sort()

Step 3

Create string from sorted characters.

String(charArray)

Examples

Sort your name in ascending order

In the following program, we take a string value in str variable, say you name, and sort the characters in the string in ascending order using sort() function.

Kotlin Program

fun main() {
    val str = "Apple Banana"
    val charArray = str.toCharArray()
    charArray.sort()
    val orderedString = String(charArray)
    println(orderedString)
}

Output

 ABaaaelnnpp

Sort your name in descending order

In the following program, we take a string value in str variable, say your name, and sort the characters in the string in descending order using sortDescending() function.

Kotlin Program

fun main() {
    val str = "Apple Banana"
    val charArray = str.toCharArray()
    charArray.sortDescending()
    val orderedString = String(charArray)
    println(orderedString)
}

Output

ppnnleaaaBA