29

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
  • 20,117
  • 14
  • 67
  • 113
madagascar
  • 309
  • 1
  • 3
  • 6

6 Answers6

33

Try the following:

input.replaceAll("\\s", "")
Nyavro
  • 8,806
  • 2
  • 26
  • 33
26

You can filter out all whitespace characters.

"With spaces".filterNot(_.isWhitespace)
Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85
Volodymyr Kozubal
  • 1,320
  • 1
  • 12
  • 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
  • 16,458
  • 8
  • 40
  • 83
elm
  • 20,117
  • 14
  • 67
  • 113
5
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
  • 20,103
  • 19
  • 89
  • 125
4

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
  • 304
  • 2
  • 4
0

you can use the trim method. Is very easy. visit this guide https://www.includehelp.com/scala/string-trim-method.aspx#:~:text=The%20trim()%20method%20defined,characters%20using%20the%20trim%20method.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 14 '22 at 19:04