How to remove a random word from a string in Scala

1 Answer

0 votes
import scala.util.Random

object Main extends App {
  def removeRandomWord(input: String): String = {
    val words = input.split(" ").toList
    if (words.isEmpty) return input

    val randomIndex = Random.nextInt(words.length)
    val updatedWords = words.patch(randomIndex, Nil, 1) // Remove the randomly selected word

    updatedWords.mkString(" ")
  }

  val str = "I'm not clumsy The floor just hates me"
  
  val result = removeRandomWord(str)

  println(result)
}



/*
run:
   
I'm clumsy The floor just hates me
 
*/

 



answered May 5, 2025 by avibootz
...