String Processing with Apache Commons Lang 3

1. Overview

The Apache Commons Lang 3 library provides support for manipulation of core classes of the Java APIs. This support includes methods for handling strings, numbers, dates, concurrency, object reflection and more.

In addition to providing a general introduction to the library, this tutorial demonstrates methods of the StringUtils class which is used for manipulation of String instances.

2. Maven Dependency

In order to use the Commons Lang 3 library, just pull it from the central Maven repository using the following dependency:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.11</version>
</dependency>

You can find the latest version of this library here.

3. StringUtils

The StringUtils class provides methods for null-safe operations on strings.

Many methods of this class have corresponding ones defined in class java.lang.String, which are not null-safe. However, this section will instead focus on several methods that do not have equivalents in the String class.

4. The containsAny Method

The containsAny method checks if a given String contains any character in the given set of characters. This set of characters can be passed in the form of a String or char varargs.

The following code fragment demonstrates the use of two overloaded flavors of this method with result verification:

String string = "maixuanviet.com";
boolean contained1 = StringUtils.containsAny(string, 'a', 'b', 'c');
boolean contained2 = StringUtils.containsAny(string, 'x', 'y', 'z');
boolean contained3 = StringUtils.containsAny(string, "abc");
boolean contained4 = StringUtils.containsAny(string, "xyz");
 
assertTrue(contained1);
assertFalse(contained2);
assertTrue(contained3);
assertFalse(contained4);

5. The containsIgnoreCase Method

The containsIgnoreCase method checks if a given String contains another String in a case insensitive manner.

The following code fragment verifies that the String “maixuanviet.com” comprises “VIETMX” when upper and lower case is ignored:

String string = "maixuanviet.com";
boolean contained = StringUtils.containsIgnoreCase(string, "VIETMX");
 
assertTrue(contained);

6. The countMatches Method

The counterMatches method counts how many times a character or substring appears in a given String.

The following is a demonstration of this method, confirming that ‘w’ appears four times and “com” does twice in the String “welcome to www.maixuanviet.com”:

String string = "welcome to www.maixuanviet.com";
int charNum = StringUtils.countMatches(string, 'a');
int stringNum = StringUtils.countMatches(string, "com");
 
assertEquals(4, charNum);
assertEquals(2, stringNum);

7. Appending and Prepending Method

The appendIfMissing and appendIfMissingIgnoreCase methods append a suffix to the end of a given String if it does not already end with any of the passed-in suffixes in a case sensitive and insensitive manner respectively.

Similarly, the prependIfMissing and prependIfMissingIgnoreCase methods prepend a prefix to the beginning of a given String if it does not start with any of the passed-in prefixes.

In the following example, the appendIfMissing and prependIfMissing methods are used to add a suffix and prefix to the String “maixuanviet.com” without these affixes being repeated:

String string = "maixuanviet.com";
String stringWithSuffix = StringUtils.appendIfMissing(string, ".com");
String stringWithPrefix = StringUtils.prependIfMissing(string, "www.");
 
assertEquals("maixuanviet.com", stringWithSuffix);
assertEquals("www.maixuanviet.com", stringWithPrefix);

8. Case Changing Method

The String class already defines methods to convert all characters of a String to uppercase or lowercase. This subsection only illustrates the use of methods changing the case of a String in other ways, including swapCasecapitalize and uncapitalize.

The swapCase method swaps the case of a String, changing uppercase to lowercase and lowercase to uppercase:

String originalString = "maixuanviet.COM";
String swappedString = StringUtils.swapCase(originalString);
 
assertEquals("MAIXUANVIET.com", swappedString);

The capitalize method converts the first character of a given String to uppercase, leaving all remaining characters unchanged:

String originalString = "maixuanviet";
String capitalizedString = StringUtils.capitalize(originalString);
 
assertEquals("Maixuanviet", capitalizedString);

The uncapitalize method converts the first character of the given String to lowercase, leaving all remaining characters unchanged:

String originalString = "Maixuanviet";
String uncapitalizedString = StringUtils.uncapitalize(originalString);
 
assertEquals("maixuanviet", uncapitalizedString);

9. Reversing Method

The StringUtils class defines two methods for reversing strings: reverse and reverseDelimited. The reverse method rearranges all characters of a String in the opposite order, while the reverseDelimited method reorders groups of characters, separated by a specified delimiter.

The following code fragment reverses the string “maixuanviet” and validates the outcome:

String originalString = "maixuanviet";
String reversedString = StringUtils.reverse(originalString);
 
assertEquals("gnudleab", reversedString);

With the reverseDelimited method, characters are reversed in groups instead of individually:

String originalString = "www.maixuanviet.com";
String reversedString = StringUtils.reverseDelimited(originalString, '.');
 
assertEquals("com.maixuanviet.www", reversedString);

10. The rotate() Method

The rotate() method circularly shifts characters of a String a number of positions. The code fragment below moves all characters of the String “maixuanviet” four positions to the right and verifies the result:

String originalString = "maixuanviet";
String rotatedString = StringUtils.rotate(originalString, 4);
 
assertEquals("dungbael", rotatedString);

11. The difference Method

The difference method compares two strings, returning the remainder of the second String, starting from the position where it is different from the first. The following code fragment compares two Strings: “VietMX Tutorials” and “VietMX Courses” in both directions and validates the outcome:

String tutorials = "VietMX Tutorials";
String courses = "VietMX Courses";
String diff1 = StringUtils.difference(tutorials, courses);
String diff2 = StringUtils.difference(courses, tutorials);
 
assertEquals("Courses", diff1);
assertEquals("Tutorials", diff2);

12. Conclusion

This tutorial introduces String processing in the Apache Commons Lang 3 and goes over the main APIs we can use out of the StringUtils library class.

As always, the implementation of all examples and code snippets given above can be found in the GitHub project.

Related posts:

Using the Map.Entry Java Class
Batch Processing with Spring Cloud Data Flow
So sánh ArrayList và LinkedList trong Java
Spring @Primary Annotation
Java Program to Implement Find all Forward Edges in a Graph
Spring Boot - Unit Test Cases
Spring Security Remember Me
Java Program to Check if a Given Graph Contain Hamiltonian Cycle or Not
Java String to InputStream
Entity To DTO Conversion for a Spring REST API
Guide to PriorityBlockingQueue in Java
Java Program to Check whether Undirected Graph is Connected using DFS
Python String istitle()
Comparing Two HashMaps in Java
Spring MVC + Thymeleaf 3.0: New Features
Hướng dẫn sử dụng lớp Console trong java
Generic Constructors in Java
Java Program to Check whether Undirected Graph is Connected using BFS
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Java Program to Implement Strassen Algorithm
Java Program to Decode a Message Encoded Using Playfair Cipher
Cachable Static Assets with Spring MVC
So sánh HashMap và Hashtable trong Java
Mapping a Dynamic JSON Object with Jackson
Custom Cascading in Spring Data MongoDB
Spring Boot Annotations
SOAP Web service: Authentication trong JAX-WS
Java Program to Implement a Binary Search Tree using Linked Lists
Java Program to Implement Multi-Threaded Version of Binary Search Tree
Convert Hex to ASCII in Java
Java Program to Test Using DFS Whether a Directed Graph is Weakly Connected or Not
Java Program to Find the Number of Ways to Write a Number as the Sum of Numbers Smaller than Itself