To sort characters in a string in Kotlin, you can convert the string to a list of characters, sort the list, and then join the characters back into a string.
In this example,
str
.toCharArray()
function.sorted()
function.joinToString()
function.fun main() {
val str = "hello world"
val sortedString = str.toCharArray().sorted().joinToString("")
println("Sorted string in ascending order: $sortedString")
}
Sorted string in ascending order: dehllloorw
In this example,
str
.toCharArray()
function.sortedDescending()
function.joinToString()
function.fun main() {
val str = "hello world"
val sortedString = str.toCharArray().sortedDescending().joinToString("")
println("Sorted string in descending order: $sortedString")
}
Sorted string in descending order: wroolllhed
In this tutorial, we learned How to Sort Characters in String in Kotlin language with well detailed examples.