Capitalize the first letter of each word in a String using Java


On this page, we will learn how to capitalize the first letter of each word in a String using Java. It is almost similar to the previous tutorial Capitalize the first letter of a String.

Capitalize the first letter of each word in a String using Java

Info: We can use the regex "\\s+" expression instead of splitting the words on white space " ".

1. Java 8 Stream API

We can use the Java 8 Stream API and its map(Function<? super T, ? extends R> mapper) method to perform the task in an efficient way.

CapitalizeAll.java
package org.websparrow;

import java.util.Arrays;
import java.util.function.Supplier;
import java.util.stream.Collectors;

public class CapitalizeAll {

    public static void main(String[] args) {

        final String foo = "new delhi is the capital city of india.";

        String output = Arrays.stream(foo.split(" "))
                .map(c -> c.substring(0, 1).toUpperCase() + c.substring(1))
                .collect(Collectors.joining(" "));

        System.out.println(output);
    }
}
console
New Delhi Is The Capital City Of India.

2. Java <= 7

If you are not using JDK 8, you can also do it in a different way.

CapitalizeAll1.java
package org.websparrow;

public class CapitalizeAll1 {

    public static void main(String[] args) {

        final String str = "sorry, i'm not using java 8.";
        String[] strArr = str.split(" ");
        String result = "";
        for (String s : strArr) {
            result = result + s.substring(0, 1).toUpperCase() + s.substring(1) + " ";
        }
		
        System.out.println(result);
    }
}
console
Sorry, I'm Not Using Java 8.

3. Apache Commons Lang 3

In Apache commons-lang3 library, there is a WordUtils.capitalize(String str) API that capitalizes the first letter of each word of a string, but it is deprecated from the 3.6.0 version. Click for more detail.

// Apache Commons Lang 3, WordUtils
final String foo = WordUtils.capitalize("cow");
System.out.println(foo); // Cow

final String boo = WordUtils.capitalize("i'm a holy cow.");
System.out.println(boo); // I'm A Holy Cow.

References

  1. Java – Capitalize the first letter of a String
  2. StringUtils- Apache Commons Lang 3
  3. WordUtils- Apache Commons Lang 3

Similar Posts

About the Author

Atul Rai
I love sharing my experiments and ideas with everyone by writing articles on the latest technological trends. Read all published posts by Atul Rai.