[Capitalize_1st] Capitalize the First Letter of a String in Java (#12885)

This commit is contained in:
Kai Yuan 2022-10-20 03:31:27 +02:00 committed by GitHub
parent bf1f0aa3da
commit b8481873e9
2 changed files with 55 additions and 2 deletions

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-string-operations-5</artifactId>
<version>0.1.0-SNAPSHOT</version>
@ -14,6 +14,13 @@
<version>0.0.1-SNAPSHOT</version>
</parent>
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${apache.commons.lang3.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@ -30,6 +37,7 @@
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
<apache.commons.lang3.version>3.12.0</apache.commons.lang3.version>
</properties>
</project>

View File

@ -0,0 +1,45 @@
package com.baeldung.capitalizethefirstletter;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.*;
public class CapitalizeTheFirstLetterUnitTest {
private static final String EMPTY_INPUT = "";
private static final String EMPTY_EXPECTED = "";
private static final String INPUT = "hi there, Nice to Meet You!";
private static final String EXPECTED = "Hi there, Nice to Meet You!";
@Test
void givenString_whenCapitalizeUsingSubString_shouldGetExpectedResult() {
String output = INPUT.substring(0, 1).toUpperCase() + INPUT.substring(1);
assertEquals(EXPECTED, output);
assertThrows(IndexOutOfBoundsException.class, () -> EMPTY_INPUT.substring(1));
}
@Test
void givenString_whenCapitalizeUsingRegexReplace_shouldGetExpectedResult() {
String output = Pattern.compile("^.").matcher(INPUT).replaceFirst(m -> m.group().toUpperCase());
assertEquals(EXPECTED, output);
String emptyOutput = Pattern.compile("^.").matcher(EMPTY_INPUT).replaceFirst(m -> m.group().toUpperCase());
assertEquals(EMPTY_EXPECTED, emptyOutput);
}
@Test
void givenString_whenCapitalizeUsingApacheCommons_shouldGetExpectedResult() {
String output = StringUtils.capitalize(INPUT);
assertEquals(EXPECTED, output);
String emptyOutput = StringUtils.capitalize(EMPTY_INPUT);
assertEquals(EMPTY_EXPECTED, emptyOutput);
String nullOutput = StringUtils.capitalize(null);
assertNull(nullOutput);
}
}