'Remove whitespaces in string with Scala

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.



Solution 1:[1]

Try the following:

input.replaceAll("\\s", "")

Solution 2:[2]

You can filter out all whitespace characters.

"With spaces".filterNot(_.isWhitespace)

Solution 3:[3]

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

str.split("\\s+").mkString

Solution 4:[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> 

Solution 5:[5]

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(" +", "") 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nyavro
Solution 2 Branislav Lazic
Solution 3 thebluephantom
Solution 4 TheKojuEffect
Solution 5 azatprog