BAEL-7055: How can I capitalize the first letter of each word in a string? (#14927)

Co-authored-by: Mo Helmy <135069400+BenHelmyBen@users.noreply.github.com>
This commit is contained in:
Azhwani 2023-10-27 08:46:04 +02:00 committed by GitHub
parent d9c72a1c1a
commit 16b931c4df
2 changed files with 78 additions and 0 deletions

View File

@ -0,0 +1,40 @@
package com.baeldung.capitalizefirstcharactereachword;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
class CapitalizeFirstCharacterEachWordUtils {
static String usingCharacterToUpperCaseMethod(String input) {
if (input == null || input.isEmpty()) {
return null;
}
return Arrays.stream(input.split("\\s+"))
.map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1))
.collect(Collectors.joining(" "));
}
static String usingStringToUpperCaseMethod(String input) {
if (input == null || input.isEmpty()) {
return null;
}
return Arrays.stream(input.split("\\s+"))
.map(word -> word.substring(0, 1).toUpperCase() + word.substring(1))
.collect(Collectors.joining(" "));
}
static String usingStringUtilsClass(String input) {
if (input == null || input.isEmpty()) {
return null;
}
return Arrays.stream(input.split("\\s+"))
.map(StringUtils::capitalize)
.collect(Collectors.joining(" "));
}
}

View File

@ -0,0 +1,38 @@
package com.baeldung.capitalizefirstcharactereachword;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;
class CapitalizeFirstCharacterEachWordUtilsUnitTest {
@Test
void givenString_whenUsingCharacterToUpperCaseMethod_thenCapitalizeFirstCharacter() {
String input = "hello baeldung visitors";
assertEquals("Hello Baeldung Visitors", CapitalizeFirstCharacterEachWordUtils.usingCharacterToUpperCaseMethod(input));
}
@Test
void givenString_whenUsingSubstringMethod_thenCapitalizeFirstCharacter() {
String input = "Hi, my name is azhrioun";
assertEquals("Hi, My Name Is Azhrioun", CapitalizeFirstCharacterEachWordUtils.usingStringToUpperCaseMethod(input));
}
@Test
void givenString_whenUsingStringUtilsClass_thenCapitalizeFirstCharacter() {
String input = "life is short the world is wide";
assertEquals("Life Is Short The World Is Wide", CapitalizeFirstCharacterEachWordUtils.usingStringUtilsClass(input));
}
@Test
void givenString_whenUsingWordUtilsClass_thenCapitalizeFirstCharacter() {
String input = "smile sunshine is good for your teeth";
assertEquals("Smile Sunshine Is Good For Your Teeth", WordUtils.capitalizeFully(input));
}
}