Capitalize First letter of each word in a String in Java | Camel Case

In this article we will discuss how to capitalize first letter of each word in a String.Suppose given string is,

this is the sample string

Now after converting first letter of each word, string will become,

This Is The Sample String

This type of String is also called Camel Case.

Algorithm For Capitalizing First Letter of Each Word in String

  • Iterate over the string from beginning to end
    • For each character check its a white space or not.If its a white space then update a flag IS_SPACE true.
    • If its a character between ‘a’ to ‘z’ and flag IS_SPACE is true then just convert this character to upper case.

Complete code in Java is as follows,

package com.thispointer.java.string.examples;

public class CaseConverter {

	/*
	 * Convert Given String to Camel Case i.e.
	 * Capitalize first letter of every word to upper case
	 */
	String camelCase(String str)
	{
		StringBuilder builder = new StringBuilder(str);
		// Flag to keep track if last visited character is a 
		// white space or not
		boolean isLastSpace = true;
		
		// Iterate String from beginning to end.
		for(int i = 0; i < builder.length(); i++)
		{
			char ch = builder.charAt(i);
			
			if(isLastSpace && ch >= 'a' && ch <='z')
			{
				// Character need to be converted to uppercase
				builder.setCharAt(i, (char)(ch + ('A' - 'a') ));
				isLastSpace = false;
			}
			else if (ch != ' ')
				isLastSpace = false;
			else
				isLastSpace = true;
		}
	
		return builder.toString();
	}
	public static void main(String[] args) {
		
		CaseConverter converter = new CaseConverter();
		
		String str = converter.camelCase("This is the sample string");
		
		System.out.println(str);

	}

}

 

 

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top