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:
Using the replaceAll() method above will remove all spaces in our string, including non-visible characters like tab, \n, etc.
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:
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():
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.
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.