Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension function of String class

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.

like image 855
MissAmna Avatar asked Jul 07 '18 15:07

MissAmna


3 Answers

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

Then:

println("14q36w25e".ascending())  // output "123456eqw"
like image 98
Geno Chen Avatar answered Oct 20 '22 04:10

Geno Chen


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

like image 4
Avijit Karmakar Avatar answered Oct 20 '22 04:10

Avijit Karmakar


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.

like image 2
Pawel Avatar answered Oct 20 '22 03:10

Pawel