How to remove duplicate white spaces in string using Java?

brainless picture brainless · Oct 18, 2010 · Viewed 152.6k times · Source

How to remove duplicate white spaces (including tabs, newlines, spaces, etc...) in a string using Java?

Answer

aioobe picture aioobe · Oct 18, 2010

Like this:

yourString = yourString.replaceAll("\\s+", " ");

For example

System.out.println("lorem  ipsum   dolor \n sit.".replaceAll("\\s+", " "));

outputs

lorem ipsum dolor sit.

What does that \s+ mean?

\s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says "one or more of those". Thus the above code will collapse all "whitespace substrings" longer than one character, with a single space character.


Source: Java: Removing duplicate white spaces in strings