How to sort a string with digits and letters (digits before letters) in Scala

1 Answer

0 votes
object CustomSort {
  def customSort(input: String): String = {
    val chars = input.toCharArray.sorted(Ordering.by[Char, (Boolean, Char)](ch => (!ch.isDigit, ch)))
    new String(chars)
  }

  def main(args: Array[String]): Unit = {
    val input = "d2a4b3c1"
    val sortedInput = customSort(input)

    println(s"Custom sorted string: $sortedInput")
  }
}



 
/*
run:

Custom sorted string: 1234abcd

*/

 



answered May 26, 2025 by avibootz
...