Java program to capitalize first letter of every word in a sentence


 Hello readers,

Today i came across an elementary interview question on Java where the user was given a sentence and he was asked to capitalize the first letter of each word in the sentence.

For e.g.

If the input text was "this is java program".

Then the output should be "This Is Java Program".



Let's try to solve this in this blog post.

There are 2 ways which comes to my mind as of now:


Approach 1: Iterating character by character and capitalizing the first letter:

package test;

public class Test {


public static void main(String[] args) {

String inputStr="this is java program";

String[] splitText=inputStr.split(" ");

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

for(int j=0;j<splitText[i].length();j++) {

if(j==0) 

{

String firstChar=""+splitText[i].charAt(j);

System.out.print(firstChar.toUpperCase());

}else {

System.out.print(splitText[i].charAt(j));

}

}

System.out.print(" ");

}

}

}



Approach 2: Using an Optimized approach 

package test;

public class Test {

public static void main(String[] args) {

String inputStr="this is java program";

String splitText[]=inputStr.split(" ");

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

//Capitalizing the first letter

String firstLetter=(splitText[i].charAt(0)+"").toUpperCase();

//Printing the rest letters

String restLetter=splitText[i].substring(1);

System.out.print(firstLetter+restLetter+" ");

}

}

}

 

Hope these approaches help you crack your next coding interview. All the best!

Follow Me on Social Media

Advertisement
FREE Sales CRM Software

Fully customizable CRM Software for Freelancers and Small Businesses

Signup for Free

Sign up for DigitalOcean Cloud

Get FREE $200 credits, deploy your hobby projects for Free

DigitalOcean Referral Badge
Sign up for Hostinger Cloud or VPS plans and get upto 20% Discount