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:
public static String capitalize(String s) {
String[] words = s.split(" ");
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
WordUtils
class from the Apache Commons Lang library:
import org.apache.commons.lang3.text.WordUtils;
...
String s = "this is a test string";
String capitalized = WordUtils.capitalizeFully(s);
- Using a regular expression:
public static String capitalize(String s) {
return s.replaceAll("\\b\\w", m -> m.toString().toUpperCase());
}
I hope this helps! Let me know if you have any questions.