How to sort a string with digits and letters (letters before digits) 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: abcd1234

*/

 



answered May 26, 2025 by avibootz
...