brainless brainless - 11 months ago 71
Java Question

How to remove duplicate white spaces in string using Java?

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

Answer Source

Like this:

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

For example

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


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