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;
public static String initials(final String str, final char... delimiters)
final String str
: stringfinal char... delimiters
: set of delimiters to determine words from the given stringThe method returns initials as a 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.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, ','));}}
The method returns Hehay
. The output string contains the initial character of every word delimited by whitespace.
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.
Original String - Hello educative how are you?
Initials - Hehay
Original String - Hello educative,how are you?
Initials - Hh