Frequently Asked Java Program 24: Java Program to Capitalize First Character of Each Word in a String Sentence

Problem Statement:

Input:

make selenium easy

Output:

Make Selenium Easy

Convert first character of each word into upper case.

Solution:

Logic:

  1. A sentence is a collection of words generally separated by a white space. We can extract words of given sentence using split method.
  2.  Now extract first character of first word and check if it is not uppercase already. If it is not, convert first char to upper case and append remaining characters of word. we can use subString method. If it is already in uppercase, append entire word. AT last append a whitespace. Repeat the same for all words.

Java Program:

 

Output:

Please enter the string to Capitalize first char of each word:
make selenium easy
You entered: make selenium easy
Output is :Make Selenium Easy
=============================================================
Please enter the string to Capitalize first char of each word:
Make Selenium Easy
You entered: Make Selenium Easy
Output is :Make Selenium Easy
=============================================================
Please enter the string to Capitalize first char of each word:
make selenium easy 123
You entered: make selenium easy 123
Output is :Make Selenium Easy 123
=============================================================
Please enter the string to Capitalize first char of each word:
make selenium easy &special
You entered: make selenium easy &special
Output is :Make Selenium Easy &special
=============================================================
Please enter the string to Capitalize first char of each word:
selenium
You entered: selenium
Output is :Selenium
=============================================================

Note- A Java library named Apache Commons provides a class "WordUtils" provides method to achieve this. But in interview, it is expected to solve with logic instead of using built in methods.

#HappyCoding

Author: Amod Mahajan

My name is Amod Mahajan and I am an IT employee with 4+ years of experience in Software testing and staying in Bengaluru. My area of interest is Automation testing. I started from basics and went throw so many selenium tutorials. Thanks to Mukesh Otwani as his tutorials are easy and cover basics to advance. I have habit of exploring concepts by deep diving. I used to make notes. I thought of sharing my knowledge through posts and now I am here. #KeepLearning #ShareLearning