javastringwhitespace

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?


Solution

  • 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.