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.
Asked
Active
Viewed 7,176 times
5

Avijit Karmakar
- 8,890
- 6
- 44
- 59

MissAmna
- 317
- 5
- 13
5 Answers
7
fun String.ascending() = String(toCharArray().sortedArray())
Then:
println("14q36w25e".ascending()) // output "123456eqw"

Geno Chen
- 4,916
- 6
- 21
- 39
4
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

Avijit Karmakar
- 8,890
- 6
- 44
- 59
2
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.

Pawel
- 15,548
- 3
- 36
- 36
-
why do you use the apply ? why not `toCharArray().sort()` directly ? – crgarridos Jul 07 '18 at 16:31
-
1`sort()` returns `Unit`, `apply` returns receiver object (`CharArray`). – Pawel Jul 07 '18 at 16:32
2
I have one more:
fun String.inAscending(): String = toMutableList().sortedBy { it }.joinToString("")
And better:
fun String.ascending(): String = toMutableList().sorted().joinToString("")

Peter Hall
- 53,120
- 14
- 139
- 204
0
In my opinion, do it in kotlin way i.e
fun String.sortAscending() = toCharArray().sortedBy{ it }.joinToString("")

SVB-knowmywork
- 123
- 1
- 9