What is the WordUtils.initials method in Java?

initials is a static method of the WordUtils class that is used to get the initial character from each word in a given string. The method optionally takes in a list of delimiters to determine the words in the given string. If no delimiters are specified, the default delimiter used is whitespace.

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;

Syntax

public static String initials(final String str, final char... delimiters)

Parameters

  • final String str: string
  • final char... delimiters: set of delimiters to determine words from the given string

Return value

The method returns initials as a string.

Code

import org.apache.commons.text.WordUtils;
public class Main {
public static void main(String[] args) {
String string = "Hello educative how are you?";
System.out.println("Original String - " + string);
System.out.println("Initials - " + WordUtils.initials(string));
System.out.println();
string = "Hello educative,how are you?";
System.out.println("Original String - " + string);
System.out.println("Initials - " + WordUtils.initials(string, ','));
}
}

Explanation

  • string = “Hello educative how are you?”

The method returns Hehay. The output string contains the initial character of every word delimited by whitespace.

  • string = “Hello educative,how are you?”

The method returns Hh. The output string contains the initial character of every word delimited by a comma. There are two words where the comma is considered the delimiter.

Expected output

Original String - Hello educative how are you?
Initials - Hehay

Original String - Hello educative,how are you?
Initials - Hh

Free Resources