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.
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?