How to remove duplicate spaces from a string in Scala

2 Answers

0 votes
import scala.util.matching.Regex

object Main extends App {
  var s = "scala   rust     golang      c#   java c    c++   python"
  
  val whitespaceRegex = new Regex("\\s+")
  s = whitespaceRegex.replaceAllIn(s, " ")
  
  println(s)
}

  
  
/*
run:
  
scala rust golang c# java c c++ python
  
*/

 



answered Oct 14, 2024 by avibootz
0 votes
import scala.util.matching.Regex

object RemoveAllOccurrencesOfWordFromString_Scala extends App {
  var s = "scala c# rust java c c++ java java golang python"
  val remove = "java"
 
  s = s.replaceAll(remove, "")

  val whitespaceRegex = new Regex("\\s+")
  s = whitespaceRegex.replaceAllIn(s, " ")
 
  println(s)
}


   
/*
run:
   
scala c# rust c c++ golang python
   
*/

 



answered Oct 14, 2024 by avibootz
...