lang3

Capitalize words of a string

This is an example of how to capitalize the words of a String. We are using the org.apache.commons.lang3.text.WordUtils Class, that provides operations on Strings that contain words. The Class tries to handle null input gracefully. An exception will not be thrown for a null input. Trying to capitalize the words of a String implies that you should:

  • Use capitalize(String str) API method of WordUtils to capitalize all the whitespace separated words in a String.
  • Then use the capitalizeFully(String str) method of WordUtils. It converts all the whitespace separated words in a String into capitalized words, that is each word is made up of a titlecase character and then a series of lowercase characters.

Let’s take a look at the code snippet that follows:  

package com.javacodegeeks.snippets.core;

import org.apache.commons.lang3.text.WordUtils;
 
public class CapitilizeWords {
	
    public static void main(String[] args) {

  
    	// capitalize method capitalizes only the letters after space 

  String string = WordUtils.capitalize("JAVA Programming is COOL");

  System.out.println("Capitilize example 1 = " + string);
 

  // capitalizeFully method capitalizes the letters after space and the rest letters turn to lower case 

  string = WordUtils.capitalizeFully("JAVA Programming is COOL");

  System.out.println("Capitilize example 2 = " + string);
    }
}

Output:

Capitilize example 1 = JAVA Programming Is COOL
Capitilize example 2 = Java Programming Is Cool

  
This was an example of how to capitalize the words of a String in Java.

Byron Kiourtzoglou

Byron is a master software engineer working in the IT and Telecom domains. He is an applications developer in a wide variety of applications/services. He is currently acting as the team leader and technical architect for a proprietary service creation and integration platform for both the IT and Telecom industries in addition to a in-house big data real-time analytics solution. He is always fascinated by SOA, middleware services and mobile development. Byron is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

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

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
David Guiney
David Guiney
7 years ago

WordUtils is now deprecated in lang3. There was another method that took an array of chars which acted as delimiters

E.g. Str1 = “My new email address is john_doe@mailserver.com

WordUtils.CapitalizeFully(Str1, new char[]{”, ‘_’, ‘@’, ‘.’});
Would give you:
“My New Email Address Is John_Doe@Mailserver.Com

What can I do in StringUtils (that is now being suggested for capitalize) to implement this?

Back to top button