madagascar
madagascar

Reputation: 309

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.

Upvotes: 29

Views: 46274

Answers (6)

Volodymyr Kozubal
Volodymyr Kozubal

Reputation: 1400

You can filter out all whitespace characters.

"With spaces".filterNot(_.isWhitespace)

Upvotes: 27

azatprog
azatprog

Reputation: 304

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

Upvotes: 4

elm
elm

Reputation: 20415

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

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

Upvotes: 7

TheKojuEffect
TheKojuEffect

Reputation: 21081

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> 

Upvotes: 5

Nyavro
Nyavro

Reputation: 8866

Try the following:

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

Upvotes: 34

Related Questions