Skip to content

Commit 2ff7d51

Browse files
Merge pull request #1551 from yadavan88/collapse-spaces
Collapse multiple spaces in a string
2 parents 149238e + 8dd1324 commit 2ff7d51

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package com.baeldung.scala.strings.removemultispace
2+
3+
object RemoveMultipleSpaces {
4+
def usingReplaceAll(str: String): String = {
5+
str.trim.replaceAll("\\s+", " ")
6+
}
7+
8+
def usingSplit(str: String): String = {
9+
str.trim.split("\\s+").mkString(" ")
10+
}
11+
12+
def usingZip(str: String): String = {
13+
if (str.trim.isEmpty) {
14+
str.trim
15+
} else {
16+
val zipped = str.trim.zip(str.trim.tail)
17+
str.trim.head + zipped.collect {
18+
case (a, b) if !(a == ' ' && b == ' ') => b
19+
}.mkString
20+
}
21+
}
22+
23+
def usingStringBuilder(str: String): String = {
24+
val sb = new StringBuilder
25+
var lastCharWasSpace = false
26+
27+
for (c <- str.trim) {
28+
if (c != ' ' || !lastCharWasSpace) sb.append(c)
29+
lastCharWasSpace = c == ' '
30+
}
31+
sb.toString
32+
}
33+
34+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.scala.strings.removemultispace
2+
3+
import org.scalatest.flatspec.AnyFlatSpec
4+
import org.scalatest.matchers.should.Matchers
5+
import org.scalatest.prop.TableDrivenPropertyChecks
6+
7+
class RemoveMultipleSpacesUnitTest
8+
extends AnyFlatSpec
9+
with Matchers
10+
with TableDrivenPropertyChecks {
11+
12+
private val table = Table(
13+
("input string", "expected"),
14+
(" too many spaces ", "too many spaces"),
15+
(" ", ""),
16+
("a", "a"),
17+
("a ", "a"),
18+
("", "")
19+
)
20+
21+
private val functions = Seq(
22+
("usingReplaceAll", RemoveMultipleSpaces.usingReplaceAll),
23+
("usingSplit", RemoveMultipleSpaces.usingSplit),
24+
("usingZip", RemoveMultipleSpaces.usingZip),
25+
("usingStringBuilder", RemoveMultipleSpaces.usingStringBuilder)
26+
)
27+
it should "remove multiple spaces with a single space in the string" in {
28+
forAll(table) { (input, expected) =>
29+
functions.map { (name, fn) =>
30+
withClue(
31+
s"Failed for the input string ${input} in the function ${name}"
32+
) {
33+
fn(input) shouldBe expected
34+
}
35+
}
36+
}
37+
}
38+
39+
}

0 commit comments

Comments
 (0)