Even for "simple" code, I would use libraries. The thing is not the code per se, but the already existing test cases covering exceptional cases. This could be null
, empty strings, strings in other languages.
The word manipulation part has been moved out ouf Apache Commons Lang. It is now placed in Apache Commons Text. Get it via https://search.maven.org/artifact/org.apache.commons/commons-text.
You can use WordUtils.capitalize(String str) from Apache Commons Text. It is more powerful than you asked for. It can also capitalize fulle (e.g., fixing "oNe tousand only"
).
Since it works on complete text, one has to tell it to capitalize only the first word.
WordUtils.capitalize("one thousand only", new char[0]);
Full JUnit class to enable playing with the functionality:
package io.github.koppor;
import org.apache.commons.text.WordUtils;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class AppTest {
@Test
void test() {
assertEquals("One thousand only", WordUtils.capitalize("one thousand only", new char[0]));
}
}