How do I capitalize each word in a string?

This examples show you how to capitalize a string. We use methods from WordUtils class provided by the Apache commons-text;. We can use the WordUtils.capitalize(str) or WordUtils.capitalizeFully(str).

Let’s see an example below:

package org.kodejava.example.commons.text;

import org.apache.commons.text.WordUtils;

public class WordCapitalize {
    public static void main(String[] args) {
        // Capitalizes all the whitespace separated words in a string,
        // only the first letter of each word is capitalized.
        String str = WordUtils.capitalize(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);

        // Capitalizes all the whitespace separated words in a string
        // and the rest string to lowercase.
        str = WordUtils.capitalizeFully(
                "The quick brown fox JUMPS OVER the lazy dog.");
        System.out.println("str = " + str);
    }
}

And here are the result of the program:

str = The Quick Brown Fox JUMPS OVER The Lazy Dog.
str = The Quick Brown Fox Jumps Over The Lazy Dog.

Maven Dependencies

<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-text/1.7/commons-text-1.7.jar -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.7</version>
</dependency>

Maven Central

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.