Java Program to Capitalize the first character of each word in a String

·

1 min read

Java Program to Capitalize the first character of each word in a String

To better understand this concept, it's good to have some basic understanding of Java Strings and the common methods associated with Strings.

Here's the code

public class CapitalizeWord {
    public static void main(String[] args) {

        // "create a string"
        String phrase = "Java is very interesting language to learn";

        // "store each character to a char Array"
        char[] charArray = phrase.toCharArray();
        boolean foundSpace = true;

        for (int i = 0; i < charArray.length; i++) {

            // "if the array element is a letter"
            if (Character.isLetter(charArray[i])) {

                // "check if space is present before the letter"
                if (foundSpace) {

                    // "change the letter into uppercase"
                    charArray[i] = Character.toUpperCase(charArray[i]);
                    foundSpace = false;
                }
            } else {
                // "if the new element is not a character"
                foundSpace = true;
            }
        }

        // "convert the charArray to string"
        phrase = String.valueOf(charArray);
        System.out.println(phrase);
    }
}

Thanks for taking your time to read this. I am glad to have you on board.

Buy me a cup of coffee