In this tutorial, you shall learn how to sort characters in a given string in Kotlin, using String.toCharArray() and Array.sort() functions, with the help of examples.

Kotlin – Sort characters in a string

To sort characters in a string in Kotlin, you can convert the string to a list of characters using String.toCharArray() function, sort the characters in list using List.sort(), finally join the sorted list to a string using List.joinToString().

Examples

ADVERTISEMENT

1. Sort characters in ascending order

In the following program, we take a string in str, sort the characters in the string, and print the sorted string to output.

Main.kt

fun main() {
    val str = "helloworld"
    var charArray = str.toCharArray()
    charArray.sort()
    val resultingString = charArray.joinToString(separator = "")
    println(resultingString)
}

Output

dehllloorw

2. Sort characters in descending order

In the following program, we take a string in str, sort the characters in the string in descending order, and print the sorted string to output.

To sort the list in descending order, we use List.sortDescending() function.

Main.kt

fun main() {
    val str = "helloworld"
    var charArray = str.toCharArray()
    charArray.sortDescending()
    val resultingString = charArray.joinToString(separator = "")
    println(resultingString)
}

Output

wroolllhed

Related Tutorials

Conclusion

In this Kotlin Tutorial, we learned how to sort characters in a string using string to list conversions, and list sorting.