I want to remove spaces in a string.
Input: "le ngoc ky quang" Output: "lengockyquang"
I tried the replace and replaceAll , but that didn't work.
replace
replaceAll
Try the following:
input.replaceAll("\\s", "")
You can filter out all whitespace characters.
"With spaces".filterNot((x: Char) => x.isWhitespace)
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>
Try splitting the string into any number of whitespace characters ( \\s+ ) and then re-merging the split array,
\\s+
str.split("\\s+").mkString
It's obvious that
scala> import PartialFunction.{cond => when} import PartialFunction.{cond=>when} scala> "le ngoc ky quang".filterNot(when(_) { case ' ' => true }) res0: String = lengockyquang scala> val r = """\p{Space}+""".r r: scala.util.matching.Regex = \p{Space}+ scala> "le ngoc ky quang".filterNot(when(_) { case r() => true }) res1: String = lengockyquang
According to alvinalexander, he shows how to replace more than one space with one space. You can apply the same logic, but instead of a single space, you should replace it with an empty string.
input.replaceAll(" +", "")