5

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.

0

5 Answers 5

8
fun String.ascending() = String(toCharArray().sortedArray())

Then:

println("14q36w25e".ascending())  // output "123456eqw"
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

2 Comments

why do you use the apply ? why not toCharArray().sort() directly ?
sort() returns Unit, apply returns receiver object (CharArray).
2

I have one more:

fun String.inAscending(): String = toMutableList().sortedBy { it }.joinToString("")

And better:

fun String.ascending(): String = toMutableList().sorted().joinToString("")

Comments

0

In my opinion, do it in kotlin way i.e

fun String.sortAscending() = toCharArray().sortedBy{ it }.joinToString("")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.