Google News
logo
Java Program to Capitalize the first character of each word in a String
In the following example of Java program to capitalize the first character of each word in a string :
Program :
public class CapitalizeWords {
    public static void main(String[] args) {
        String str = "the quick brown fox jumps over the lazy dog";
        // Split the string into words using space as the delimiter
        String[] words = str.split("\\s");
        StringBuilder sb = new StringBuilder();
        // Iterate through each word and capitalize the first character
        for (String word : words) {
            sb.append(Character.toUpperCase(word.charAt(0))).append(word.substring(1)).append(" ");
        }
        String capitalizedStr = sb.toString().trim();
        System.out.println(capitalizedStr);
    }
}
Output :
The Quick Brown Fox Jumps Over The Lazy Dog
In this program, we first declare a string variable str and initialize it with the string "the quick brown fox jumps over the lazy dog". We then split the string into words using the split() method with a regular expression that matches whitespace characters (\\s) as the delimiter. We create a StringBuilder object sb to build the capitalized string.

Next, we use a for loop to iterate through each word in the words array. Inside the loop, we use the toUpperCase() method of the Character class to capitalize the first character of the current word, and we append the rest of the word using the substring() method. We also append a space character after each word.

Finally, we convert the StringBuilder object to a string using the toString() method, and we remove any trailing whitespace using the trim() method. We then print the capitalized string to the console.