How to move a word to the end of a string in Scala

1 Answer

0 votes
def moveWordToEnd(s: String, word: String): String = {
  val parts = s.split("\\s+").toList

  parts.indexOf(word) match {
    case -1 =>
      parts.mkString(" ")

    case idx =>
      val without = parts.patch(idx, Nil, 1)   // remove the word
      (without :+ word).mkString(" ")
  }
}

val s = "Would you like to know more? (Explore and learn)"
val word = "like"

val result = moveWordToEnd(s, word)
println(result)

 
  
  
  
/*
run:
  
Would you to know more? (Explore and learn) like
  
*/

 

 



answered Feb 5 by avibootz
...