Skip to content

Commit cd32dfb

Browse files
committed
Added one more method
1 parent db4bbeb commit cd32dfb

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

scala-strings/src/main/scala/com/baeldung/scala/strings/capitalize/CapitalizeWords.scala

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,12 @@ object CapitalizeWords {
1717
}
1818
.mkString(" ")
1919
}
20+
21+
def capitalizeWordsPreserveSpaces(sentence: String): String = {
22+
sentence.zipWithIndex.map { (char, index) =>
23+
if(index == 0) char.toUpper
24+
else if(sentence.charAt(index-1).isSpaceChar) char.toUpper
25+
else char
26+
}.mkString
27+
}
2028
}

scala-strings/src/test/scala/com/baeldung/scala/strings/capitalize/CapitalizeWordsUnitTest.scala

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,18 @@ class CapitalizeWordsUnitTest
3939
}
4040
}
4141

42+
val tablePreservingSpace = Table(
43+
("Input", "Expected"),
44+
("This is scala 3", "This Is Scala 3"),
45+
("hello world", "Hello World"),
46+
("baeldung articles", "Baeldung Articles"),
47+
(" ", " "),
48+
("1000", "1000")
49+
)
50+
it should "capitalize every words of a sentence preserving the spaces" in {
51+
forAll(tablePreservingSpace) { (input, expected) =>
52+
CapitalizeWords.capitalizeWordsPreserveSpaces(input) shouldBe expected
53+
}
54+
}
55+
4256
}

0 commit comments

Comments
 (0)