Skip to content

Remove multiple spaces from String in Java example

Remove multiple spaces from String in Java example shows how to remove multiple consecutive spaces from string in Java using regular expression and the trim method.

How to remove multiple spaces from String in Java?

Sometimes string input contains multiple consecutive white spaces that we need to remove. Consider below given string inputs.

The first string contains multiple spaces at the start of the string, second string element contains multiple spaces at the end of the string while the third string array element contains multiple spaces at start, in between and at the end of the string.

Multiple spaces can be matched with regular expression with the “\\s+” pattern.  The “\\s” pattern matches any space character (i.e. space, tab, and new line character).  The “\\s+” pattern matches one or more space characters.

Use the replaceAll method of the String class which accepts a regular expression to replace one or more space characters with the single space to remove multiple spaces from the string as given below.

Output

Our pattern removed multiple spaces from the middle of the string, but it still left a single space at the start and end of the String. To remove that as well, use trim method along with the replaceAll method as given below.

Output

Finally, if you are using the Apache Commons library, you can use the normalizeSpace method of the StringUtils class to remove multiple spaces from the string as given below.  The normalizeSpace method first trims the string (thus removing all leading and trailing spaces from the string) and then it replaces multiple spaces with a single space.

Output

This example is a part of the Java String tutorial.

Please let me know your views in the comments section below

About the author

Leave a Reply

Your email address will not be published.