Java extracts initial characters from each word in a String using Apache Commons Text

Tags: Apache Commons Apache Commons Text WordUtils String

Introduction

In this post we learn how to use WordUtils class of Apache Commons Text library to extract initial characters from all words of a String in Java. We will show the Java code example that uses WordUtils.initials() method to extract initial letters of people names.

Setup Apache Commons Text in Java project

If you are using Gradle build then add the following dependency configuration into build.gradle file.

compile group: 'org.apache.commons', name: 'commons-text', version: '1.9'

Or add the following dependency XML tag to pom.xml file if you are using Maven build.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

Or download commons-text-1.9.jar file from Apache Commons Text download page at commons.apache.org

Java example code how to use org.apache.commons.text.WordUtils.initials()

import org.apache.commons.text.WordUtils;

public class WordUtilsInitialsExample1 {
    public static void main(String[] args) {
        String initialsString1 = WordUtils.initials("Amara Ford");
        String initialsString2 = WordUtils.initials("Ben John Lee");
        String initialsString3 = WordUtils.initials("Ben J.Lee");
        String initialsString4 = WordUtils.initials("Jocelyn");

        System.out.println(initialsString1);
        System.out.println(initialsString2);
        System.out.println(initialsString3);
        System.out.println(initialsString4);
    }
}
Output:

AF
BJL
BJ
J

WordUtils.initials() with a given set of characters to determine words

import org.apache.commons.text.WordUtils;

public class WordUtilsInitialsExample2 {
    public static void main(String[] args) {
        char[] delimiters = new char[] {' ','.'};
        String initialsString1 = WordUtils.initials("Amara Ford", delimiters);
        String initialsString2 = WordUtils.initials("Ben John Lee", delimiters);
        String initialsString3 = WordUtils.initials("Ben J.Lee", delimiters);
        String initialsString4 = WordUtils.initials("Jocelyn", delimiters);

        System.out.println(initialsString1);
        System.out.println(initialsString2);
        System.out.println(initialsString3);
        System.out.println(initialsString4);
    }
}
Output:

AF
BJL
BJL
J

Happy Coding 😊