How to move all special characters to the beginning of a string in Scala

1 Answer

0 votes
object MoveSpecialChars {
  def moveSpecialCharactersToBeginning(s: String): String = {
    val (specials, chars) = s.partition(ch => !(ch.isLetterOrDigit || ch.isWhitespace))

    specials + chars
  }

  def main(args: Array[String]): Unit = {
    val s = "c++20$c&^java*(rust) php <>/python 3.14.2"
    
    println(moveSpecialCharactersToBeginning(s))
  }
}




/*
run:

++$&^*()<>/..c20cjavarust php python 3142

*/

 



answered Dec 12, 2025 by avibootz

Related questions

...