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.
fun String.ascending() = String(toCharArray().sortedArray())
Then:
println("14q36w25e".ascending()) // output "123456eqw"
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With