Capitalize First Letter of Each Word in Java

In Java, transforming the first letter of each word in a string to uppercase (also known as title case) is a common text manipulation task. This can be useful for formatting titles, and headings, or ensuring consistency in user input. We'll explore different methods to achieve this in Java. 

Method 1: Using String.split() and Character.toUpperCase() 

This method involves splitting the string into words, capitalizing the first character of each word, and then concatenating them back together. 

Code Example

public class CapitalizeFirstLetter {
    public static String capitalizeWords(String str) {
        String[] words = str.split("\\s");
        StringBuilder capitalizedWords = new StringBuilder();

        for (String word : words) {
            String firstLetter = word.substring(0, 1).toUpperCase();
            String remainingLetters = word.substring(1).toLowerCase();
            capitalizedWords.append(firstLetter).append(remainingLetters).append(" ");
        }

        return capitalizedWords.toString().trim();
    }

    public static void main(String[] args) {
        String input = "hello world in java";
        String result = capitalizeWords(input);
        System.out.println(result); // Output: Hello World In Java
    }
}

Output:

Hello World In Java

Method 2: Using java.text.BreakIterator 

BreakIterator is a Java utility class that provides methods for locating boundaries, such as words, in text. This method is useful for handling complex text and different locales. 

Code Example

import java.text.BreakIterator;

public class CapitalizeFirstLetter {

    public static String capitalizeWordsWithBreakIterator(String source) {
        BreakIterator boundary = BreakIterator.getWordInstance();
        boundary.setText(source);

        int start = boundary.first();
        StringBuilder result = new StringBuilder(source.length());

        for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
            String word = source.substring(start, end);
            if (Character.isLetterOrDigit(word.charAt(0))) {
                result.append(Character.toUpperCase(word.charAt(0)))
                      .append(word.substring(1).toLowerCase());
            } else {
                result.append(word);
            }
        }

        return result.toString();
    }

    public static void main(String[] args) {
        String input = "hello world in java";
        String result = capitalizeWordsWithBreakIterator(input);
        System.out.println(result); // Output: Hello World In Java
    }
}

Output:

Hello World In Java

Method 3: Using Apache Commons Lang WordUtils.capitalizeFully() 

If you're using Apache Commons Lang, it provides a utility method WordUtils.capitalizeFully() that simplifies this task. 

Code Example 

First, add the dependency to your project:
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

Then, use the capitalizeFully() method:
import org.apache.commons.text.WordUtils;

public class CapitalizeFirstLetter {
    public static void main(String[] args) {
        String input = "hello world in java";
        String result = WordUtils.capitalizeFully(input);
        System.out.println(result); // Output: Hello World In Java
    }
}

Output:

Hello World In Java

Method 4: Using Java 8 Streams 

For a more functional approach, especially if you are using Java 8 or later, you can use streams to capitalize each word. 

Code  Example

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

public class CapitalizeEachWord {
    public static String capitalizeWords(String str) {
        return Arrays.stream(str.split("\\s+"))
                     .filter(word -> !word.isEmpty())
                     .map(word -> Character.toUpperCase(word.charAt(0)) + word.substring(1).toLowerCase())
                     .collect(Collectors.joining(" "));
    }

    public static void main(String[] args) {
        String input = "hello world in java";
        String output = capitalizeWords(input);
        System.out.println("Capitalized String: " + output);
    }
}

Output:

Hello World In Java

Comments