Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,709 questions

55,473 answers

573 users

How to extract and sort numbers from a string containing numbers and text in Scala

1 Answer

0 votes
import scala.util.matching.Regex

/**
 * Program to extract and sort integer values from a mixed string of text and numbers.
 * Demonstrates Scala's expressive regular expressions and functional Collections API.
 */
object NumberExtractorSort {

  /**
   * Extracts all contiguous digit sequences from a string and converts them to integers.
   *
   * @param input The raw string containing text and embedded numbers.
   * @return A Vector containing the extracted integers in order of appearance.
   */
  def extractNumbers(input: String): Vector[Int] = {
    // The ".r" extension method on a String compactly compiles it into a Regex object.
    // "\\d+" matches one or more contiguous ASCII digits.
    val digitPattern: Regex = "\\d+".r

    // 1. `findAllIn(input)` returns an Iterator[String] of all non-overlapping matches.
    // 2. `map(_.toInt)` safely transforms each numeric string into an integer.
    // 3. `toVector` materializes the iterator into an immutable, efficient indexed sequence.
    digitPattern.findAllIn(input).map(_.toInt).toVector
  }

  /**
   * Sorts a sequence of numbers in ascending order.
   *
   * @param numbers The collection of integers to be sorted.
   * @return A new sequence sorted in ascending order.
   */
  def sortNumbers(numbers: Vector[Int]): Vector[Int] = {
    // The `.sorted` method leverages an implicit Ordering[Int] provided by the standard library.
    // Under the hood, Scala collections use a highly optimized Timsort algorithm (O(N log N)).
    numbers.sorted
  }

  def main(args: Array[String]): Unit = {
    val inputStr = "1000withz7 and3 or 99 give42"

    // String interpolation using the 's' interpolator
    println(s"""Input String:      "$inputStr"""")

    // Extract numbers using the regex and transformation pipeline
    val extractedNums = extractNumbers(inputStr)
    // mkString formats the collection to explicitly match the requested array output style
    println(s"Extracted Numbers: ${extractedNums.mkString("[", ", ", "]")}")

    // Sort the extracted numbers into a new immutable Vector
    val sortedNums = sortNumbers(extractedNums)
    println(s"Sorted Numbers:    ${sortedNums.mkString("[", ", ", "]")}")
  }
}



/*
run:

Input String:      "1000withz7 and3 or 99 give42"
Extracted Numbers: [1000, 7, 3, 99, 42]
Sorted Numbers:    [3, 7, 42, 99, 1000]

*/

 



answered 1 day ago by avibootz
...