capitalize
is a static method of the WordUtils
class that is used to capitalize all delimiter-separated words in a string. Each word’s initial character is altered only.
WordUtils
is defined in the Apache Commons Text
package. Apache Commons Text
can be added to the Maven Project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>
For other versions of the
commons-text
package, refer to the Maven Repository.
You can import the WordUtils
class as follows:
import org.apache.commons.text.WordUtils;
public static String capitalize(final String str, final char... delimiters)
final String str
: string to be capitalizedfinal char... delimiters
: set of delimitersThis method returns a new capitalized string.
import org.apache.commons.text.WordUtils;public class Main {public static void main(String[] args) {String string = "Hello educative,how are you?";System.out.print("Delimited by whitespace - ");System.out.print(WordUtils.capitalize(string));System.out.print("\nDelimited by comma (,) - ");System.out.print(WordUtils.capitalize(string, ','));string = "lorem ipsum is a pseudo-Latin text used in web design,typography,layout,and printing in place of english to emphasise design elements over content.it's also called placeholder (or filler) text.";System.out.print("\nDelimited by comma (, and .) - ");System.out.print(WordUtils.capitalize(string, ',', '.'));}}
"Hello educative,how are you?"
[]
Applying the capitalize
function will result in: Hello Educative,how Are You?
.
The word how
is not capitalized, as it’s not delimited by whitespace.
"Hello educative,how are you?"
[',']
Applying the capitalize
function will result in: Hello educative,How are you?
Here, the comma is the delimiter and hence results in two fragments, i.e., Hello educative
and how are you?
. Capitalizing the first character of each fragment results in Hello educative,How are you?
"lorem ipsum is a pseudo-Latin text used in web design,typography,layout,and printing in place of english to emphasise design elements over content.it's also called placeholder (or filler) text."
[',', '.']
Applying the capitalize
function will result in: Lorem ipsum is a pseudo-Latin text used in web design,Typography,Layout,And printing in place of english to emphasise design elements over content.It's also called placeholder (or filler) text.
Here, the function capitalizes the first character of each fragment, separated by a comma or a full-stop.
Delimited by whitespace - Hello Educative,how Are You?
Delimited by comma (,) - Hello educative,How are you?
Delimited by comma (, and .) - Lorem ipsum is a pseudo-Latin text used in web design,Typography,Layout,And printing in place of english to emphasise design elements over content.It's also called placeholder (or filler) text.