Java Top

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

Authors Top

If you have a few years of experience in the Java ecosystem, and you’d like to share that with the community, have a look at our Contribution Guidelines.

1. Overview

In this short tutorial, we'll see how to compare strings while ignoring whitespace in Java.

2. Use replaceAll() Method

Suppose we have two strings – one containing spaces in it and the other containing only non-space characters:

String normalString = "ABCDEF";
String stringWithSpaces = " AB  CD EF ";

We can simply compare them while ignoring the spaces using the built-in replaceAll() method of the String class:

assertEquals(normalString.replaceAll("\\s+",""), stringWithSpaces.replaceAll("\\s+",""));

Using the replaceAll() method above will remove all spaces in our string, including non-visible characters like tab, \n, etc.

In addition to \s+, we can use \s.

3. Use Apache Commons Lang

Next, we can use the StringUtils class from the Apache Commons Lang library to achieve the same goal.

This class has a method deleteWhitespace(), which is used to delete all spaces in a String:

assertEquals(StringUtils.deleteWhitespace(normalString), StringUtils.deleteWhitespace(stringWithSpaces));

4. Use the StringUtils Class of Spring Framework

Finally, if our project is already using Spring Framework, we can use the StringUtils class from the org.springframework.util package.

The method to use this time is trimAllWhitespace():

assertEquals(StringUtils.trimAllWhitespace(normalString), StringUtils.trimAllWhitespace(stringWithSpaces));

We should keep in mind that if we want to compare strings where spaces have a meaning, like people's names, we shouldn't use the methods in this article. For example, the following two strings will be considered equal: “JACKIE CHAN” and “JAC KIE CHAN” and this may not be what we actually want.

5. Conclusion

In this article, we’ve seen different ways to compare strings while ignoring whitespace in Java.

As always, the example code from this article can be found over on GitHub.

Java bottom

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

>> CHECK OUT THE COURSE
Generic footer banner
Comments are closed on this article!