26

I want to remove the whitespaces in a string.

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

I tried the replace and replaceAll methods but that did't work.

elm
  • 19,337
  • 14
  • 61
  • 108
madagascar
  • 279
  • 1
  • 3
  • 6

5 Answers5

31

Try the following:

input.replaceAll("\\s", "")
Nyavro
  • 8,656
  • 2
  • 23
  • 32
22

You can filter out all whitespace characters.

"With spaces".filterNot(_.isWhitespace)
Branislav Lazic
  • 13,691
  • 8
  • 56
  • 81
Volodymyr Kozubal
  • 1,241
  • 1
  • 11
  • 16
7

Consider splitting the string by any number of whitespace characters (\\s+) and then re-concatenating the split array,

str.split("\\s+").mkString
thebluephantom
  • 14,410
  • 8
  • 36
  • 67
elm
  • 19,337
  • 14
  • 61
  • 108
4
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> 
TheKojuEffect
  • 18,635
  • 17
  • 83
  • 116
3

According to alvinalexander it shows there how to replace more than white spaces to one space. The same logic you can apply, but instead of one space you should replace to empty string.

input.replaceAll(" +", "") 
azatprog
  • 184
  • 1
  • 4