I want to create an extension function of String which takes a String and returns a new String with the characters as the first, but sorted in ascending order. How can I do this? I am new to Kotlin.
5 Answers
Extension function for printing characters of a string in ascending order
Way 1:
fun String.sortStringAlphabetically() = toCharArray().sortedArray())
Way 2:
fun String.sortStringAlphabetically() = toCharArray().sortedArrayDescending().reversedArray()
Way 3:
fun String.sortStringAlphabetically() = toCharArray().sorted().joinToString(""))
Way 4:
fun String.sortStringAlphabetically() = toCharArray().sortedBy{ it }.joinToString(""))
Then you can use this extension function by the below code:
fun main(args: Array<String>) {
print("41hjhfaf".sortStringAlphabetically())
}
Output: 14affhhj
Comments
You can combine built in extensions to do it quickly:
fun String.sortedAlphabetically() = toCharArray().apply { sort() }
First you get array of underlying characters, then you apply sort to that array and return it. You are free to cast result .toString() if You need.
2 Comments
crgarridos
why do you use the apply ? why not
toCharArray().sort() directly ?Pawel
sort() returns Unit, apply returns receiver object (CharArray).