Capitalize The First Character Of
Each Word In A String
In this java program, all the words of a sentence will be capitalized.
Here we are going to explain step by step.
Step 1: A string is taken as String st1="the red book keep on the red
table with a red paper";
Here we need to convert with the help of the Java Program to capitalize
each word in String.
Step 2: Then we have to define a string as word and st2 and each initialize
as st1=”” and word=”” and also some more variables as String first (for first the character of each word), excpetFirstChar(for entire characters except the first
character), char ch, ch1 for taking the character from each word.
Step 3: st1= st1 + "
"; in this line, space is added as here we have to take characters of
each word till space encounter, so last word of the string has no space so the
space is added.
Step 4: length=st1.length();
length of the string has been taken.
Spep 5: In the for loop we have to take one character with the help of
charAt() method and add to word variable till space is encounter. If encounter
the need to convert the first character of word capital and the rest to remain
small and this done with this statement
- first=word.substring(0,1);
- excpetFirstChar=word.substring(1);
- st2+=first.toUpperCase()+excpetFirstChar+" ";
This process will be run till the end of the sentence
Step 6 : Print the value finally.
public class CapitalizeEachWord
{
public static void
main(String args[])
{
String st1="the red
book keep on the red table with a red paper";
String st2="",
word="";
String first,
excpetFirstChar;
char ch, ch1;
int i, length, chartoint;
st1= st1 + " ";
//st1 = " " +
st1;
length=st1.length();
for(i=0; i<length;
i++)
{
ch=st1.charAt(i);
if(ch!=' ')
{
word = word + ch;
}
else
{
first=word.substring(0,1);
excpetFirstChar=word.substring(1);
st2+=first.toUpperCase()+excpetFirstChar+" ";
word="";
}
}
System.out.println("Original Sentence:" + st1);
System.out.println("Changed Sentence :" + st2);
}
}
Output:
Original Sentence: the red book keep on the red table with a red paper
Changed Sentence: The Red Book Keep On The Red Table With A Red Paper