Appearance
How to capitalize the first character of each word in a string
There are a few different approaches you can take to capitalize the first character of each word in a string in Java. Here are a few options:
- Using the
toLowerCase()andtoUpperCase()methods:
java
public static String capitalize(String s) {
if (s == null || s.trim().isEmpty()) return s;
String[] words = s.trim().split("\\s+");
StringBuilder sb = new StringBuilder();
for (String word : words) {
sb.append(word.substring(0, 1).toUpperCase());
sb.append(word.substring(1).toLowerCase());
sb.append(" ");
}
return sb.toString().trim();
}- Using the
WordUtilsclass from the Apache Commons Text library:
java
import org.apache.commons.text.WordUtils;
// Maven dependency:
// <dependency>
// <groupId>org.apache.commons</groupId>
// <artifactId>commons-text</artifactId>
// <version>1.10.0</version>
// </dependency>
String s = "this is a test string";
String capitalized = WordUtils.capitalizeFully(s);- Using a regular expression:
java
// Requires Java 9+
public static String capitalize(String s) {
if (s == null) return null;
return s.replaceAll("\\b\\w", m -> m.toString().toUpperCase());
}I hope this helps! Let me know if you have any questions.