Skip to content

Commit

Permalink
Merge pull request #1551 from yadavan88/collapse-spaces
Browse files Browse the repository at this point in the history
Collapse multiple spaces in a string
  • Loading branch information
dominiqueplante authored Sep 18, 2024
2 parents 149238e + 8dd1324 commit 2ff7d51
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.baeldung.scala.strings.removemultispace

object RemoveMultipleSpaces {
def usingReplaceAll(str: String): String = {
str.trim.replaceAll("\\s+", " ")
}

def usingSplit(str: String): String = {
str.trim.split("\\s+").mkString(" ")
}

def usingZip(str: String): String = {
if (str.trim.isEmpty) {
str.trim
} else {
val zipped = str.trim.zip(str.trim.tail)
str.trim.head + zipped.collect {
case (a, b) if !(a == ' ' && b == ' ') => b
}.mkString
}
}

def usingStringBuilder(str: String): String = {
val sb = new StringBuilder
var lastCharWasSpace = false

for (c <- str.trim) {
if (c != ' ' || !lastCharWasSpace) sb.append(c)
lastCharWasSpace = c == ' '
}
sb.toString
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.baeldung.scala.strings.removemultispace

import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import org.scalatest.prop.TableDrivenPropertyChecks

class RemoveMultipleSpacesUnitTest
extends AnyFlatSpec
with Matchers
with TableDrivenPropertyChecks {

private val table = Table(
("input string", "expected"),
(" too many spaces ", "too many spaces"),
(" ", ""),
("a", "a"),
("a ", "a"),
("", "")
)

private val functions = Seq(
("usingReplaceAll", RemoveMultipleSpaces.usingReplaceAll),
("usingSplit", RemoveMultipleSpaces.usingSplit),
("usingZip", RemoveMultipleSpaces.usingZip),
("usingStringBuilder", RemoveMultipleSpaces.usingStringBuilder)
)
it should "remove multiple spaces with a single space in the string" in {
forAll(table) { (input, expected) =>
functions.map { (name, fn) =>
withClue(
s"Failed for the input string ${input} in the function ${name}"
) {
fn(input) shouldBe expected
}
}
}
}

}

0 comments on commit 2ff7d51

Please sign in to comment.