Skip to content

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:

  1. Using the toLowerCase() and toUpperCase() 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();
}
  1. Using the WordUtils class 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);
  1. 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.

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.