Sort a String alphabetically in Kotlin
This article explores different ways to sort a String alphabetically in Kotlin.
1. Using sort() function
Since the String is immutable in Kotlin, it cannot be modified once created. The only plausible way to rearrange the characters of a string in sorted order is to get a new string. The idea is to convert the given string to a character array using the toCharArray() function and sort it using the sort() function. Then, pass the character array to the String constructor to get a new string.
|
1 2 3 4 5 6 7 8 9 |
fun main() { var str = "BADC" val chars = str.toCharArray() chars.sort() str = String(chars) println(str) } |
This can be done inline using a scope function, as shown below:
|
1 2 3 4 5 |
fun main() { var str = "BADC" str = str.toCharArray().apply { sort() }.joinToString("") println(str) } |
Or even shorter:
|
1 2 3 4 5 6 |
fun main() { var str = "BADC" str = String(str.toCharArray().apply { sort() }) println(str) } |
2. Using sorted() function
Another option is to split the string with delimiter "" to get a list of characters in the String, which then can be sorted using the sorted() function. After sorting, join the array back into a string using the joinToString() function.
|
1 2 3 4 5 |
fun main() { var str = "BADC" str = str.split("").sorted().joinToString("") println(str) } |
That’s all about sorting a String alphabetically in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)