Problem: Write a Java program to capitalize the first letter of each word of a given sentence.

Example:

Input   : java is a programming Language
Output  : Java Is A Programming Language

Method 1: By Splitting Sentence into Words Array

We can easily convert the first letter of each word of a string into uppercase by splitting the sentence into words (words array) using the split() method and applying toUpperCase() on each word.

But it’s important to note that the string in Java is immutable, so we need to re-form a new sentence using the modified word.

public class Main
{
	public static void main(String[] args) {
	    String str = "pencil programmer";
    
	    //Split sentence into words
	    String words[]=str.split("\\s");
        String newString ="";
        
        for(String w: words){
            String first = w.substring(0,1);      //First Letter
            String rest = w.substring(1);         //Rest of the letters
        
            //Concatenete and reassign after 
            //converting the first letter to uppercase
            newString+=first.toUpperCase()+ rest+ " ";  
        }  
    
        //trim to remove the last redundant blank space
        System.out.println(newString.trim());
	}
}

Output:

Pencil Programmer

Method 2: Without Splitting Sentence

We can also capitalize the first letter of every word without splitting the sentence into an array of words.

All we need to do is to look for the blank space ' ' in the sentence and capitalize the next letter (because the letter just after white space is the first letter of the next word in the sentence).

public class Main
{
	public static void main(String[] args) {
	    String oldString = "adarsh kumar";
	    String newString = "";
	    
        //Add space at starting of the old string
        //to capture the first letter of the first word.
	    oldString = " "+ oldString;
	    
	    //iterate through the characters of old string to capture white space
	    for(int i=0;i<oldString.length(); ){
	        char ch  =  oldString.charAt(i);
	        
	        /*
	          *If white space found then concatenate it along with-
	          *the upper transformation of the letter next to it.
	        */
	        if(ch == ' '){
	            newString = newString + ' ' + Character.toUpperCase(oldString.charAt(i+1));
	            i=i+2;
	        } 
	        //otherwise just concatenate without any transformation
	        else {
	            newString = newString + ch;
	            i++;
	        }
	    }
            
            //trim to remove leading blank space
	    System.out.println(newString .trim());
	}
}

Output:

Adarsh Kumar

Leave a Reply