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.

Download Code

 
This can be done inline using a scope function, as shown below:

Download Code

 
Or even shorter:

Download Code

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.

Download Code

That’s all about sorting a String alphabetically in Kotlin.