Reputation: 309
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
Reputation: 1
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.
Upvotes: 0
Reputation: 1400
You can filter out all whitespace characters.
"With spaces".filterNot(_.isWhitespace)
Upvotes: 27
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
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
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