Java Capitalize First Letter of Each Word

In this blog, we will see how to capitalize the first character of each word present in a given string. There can be two different ways to achieve our desired result. Let us see both of them one after another.

1. Using Split Function with for Loop

Code:

Output:

Code Explanation:

We have created a function char_capital which takes input_string as an argument. Then the split method is used to split the string by space(“ ”) into an array of words. The for loop is initiated for the words_string array. The first character of each word is taken and converted into uppercase, and then we add the changed string to the result_string.

Inside the main function, we have created a scanner object to take a string as input from the user and then called the char_capital method for that string.

2. Using Only for Loop

Code:

Output:

The logic for both programs are same, but they are implemented in their own different ways.

I hope you have understood the problem clearly. Please do comment below if you still have any doubts.

Leave a Comment

Your email address will not be published. Required fields are marked *