Remove spaces in a string with Scala

I want to remove spaces in a string.

Input: "le ngoc ky quang" Output: "lengockyquang" 

I tried the replace and replaceAll , but that didn't work.

+21
scala
source share
6 answers

Try the following:

 input.replaceAll("\\s", "") 
+23
source share

You can filter out all whitespace characters.

 "With spaces".filterNot((x: Char) => x.isWhitespace) 
+16
source share
 val str = "le ngoc ky quang" str.replace(" ", "") ////////////////////////////////////// scala> val str = "le ngoc ky quang" str: String = le ngoc ky quang scala> str.replace(" ", "") res0: String = lengockyquang scala> 
+3
source share

Try splitting the string into any number of whitespace characters ( \\s+ ) and then re-merging the split array,

 str.split("\\s+").mkString 
+3
source share

It's obvious that

 scala> import PartialFunction.{cond => when} import PartialFunction.{cond=>when} scala> "le ngoc ky quang".filterNot(when(_) { case ' ' => true }) res0: String = lengockyquang scala> val r = """\p{Space}+""".r r: scala.util.matching.Regex = \p{Space}+ scala> "le ngoc ky quang".filterNot(when(_) { case r() => true }) res1: String = lengockyquang 
0
source share

According to alvinalexander, he shows how to replace more than one space with one space. You can apply the same logic, but instead of a single space, you should replace it with an empty string.

 input.replaceAll(" +", "") 
0
source share

All Articles