Java replaceAll - How to replace all blank characters in a String

Today I needed a Java method to remove all the blank characters from a String. I started to write some code with a StringBuffer or a StringBuilder, then thought there must be some other way to do this. It’s not that the StringBuilder/StringBuffer approach is hard, but just that someone must have already solved this problem.

That’s when I thought of the replaceAll method of the String class, and that I might be able to use it. Sure enough, the following line of code returns a new String with all the blank characters removed:

String newName = oldName.replaceAll(" ", "");

Note that there is a blank space between the first set of double quotes in that line, and there is no space between the second set of quotes.

A note on using a regex

Because the String class replaceAll method takes a regex, you can probably replace much more complicated string patterns using this technique, but I don’t have that need currently, so I didn’t try it. As a quick example, off the top of my head, and not even typing this following code into a compiler, this next piece of Java source code should return a new String with all whitespace characters removed:

String newName = oldName.replaceAll("\\s", "");

Again, that code hasn’t been tested or even typed into a Java IDE, but hopefully it’s in the ballpark.

Post new comment

The content of this field is kept private and will not be shown publicly.