How to sort the words in a string with Scala

1 Answer

0 votes
object SortWordsWithComments:

  // Function to sort the words in a string
  def sortWordsInString(s: String): String =
    // Create a sequence to hold the words
    val words = s.split(" ")   // Words are separated by spaces

    // Enable automatic alphabetical sorting
    val sorted = words.sorted

    // Optional: ignore duplicate words
    // (Scala's `distinct` removes duplicates)
    val unique = sorted.distinct

    // Join the sorted words back into a single string
    unique.mkString(" ")

  @main def run() =
    // Test the function
    println(sortWordsInString("the quick brown fox jumps over the lazy dog"))




/*
run:

brown dog fox jumps lazy over quick the

*/

 



answered May 21 by avibootz
...