File tree Expand file tree Collapse file tree 2 files changed +73
-0
lines changed
scala-core-modules/scala-strings-2/src
main/scala/com/baeldung/scala/strings/removemultispace
test/scala/com/baeldung/scala/strings/removemultispace Expand file tree Collapse file tree 2 files changed +73
-0
lines changed Original file line number Diff line number Diff line change 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 number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments