How to extract all digits from a string in Scala

1 Answer

0 votes
object ExtractDigitsApp {

  /*
      extractDigits
      --------------
      Walks through the input string and collects only characters
      that are recognized as digits.

      Scala's `filter` method provides a clear and efficient way
      to process characters, and `Character.isDigit` ensures
      Unicode‑aware digit detection.

      The result is built using standard collection operations.
  */
  def extractDigits(s: String): String = {
    // Filter characters that are digits and convert the result back to a string
    s.filter(Character.isDigit)
  }

  def main(args: Array[String]): Unit = {
    // Example input string
    val str = "5 rustc#8go 9001 c c++ 17python"

    // Extract digits
    val digits = extractDigits(str)

    // Display results
    println(s"Original: $str")
    println(s"Digits:   $digits")
  }
}


/*
run:

Original: 5 rustc#8go 9001 c c++ 17python
Digits:   58900117

*/

 



answered Sep 17 by avibootz
...