How to Remove Duplicate White Spaces in String Using Java

How to remove duplicate white spaces in string using Java?

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

Not able to remove multiple whitespace(s) in a string in java

I can only guess that the spaces are not really space character (U+0020), but some Unicode space character, like U+00A0 NO BREAK SPACE. \s by default only matches space characters in the ASCII range, so they are not removed.

If you want to remove all Unicode spaces, you have to enable the UNICODE_CHARACTER_CLASS flag with inline construct (?U)

String myString2 = myString1.replaceAll("(?U)\\s+", "");

how to remove a distinct number of spaces from String in java?

You can replace 6 spaces with 1 space using below line:

jshell> String a = "abc      def";
a ==> "abc def"

jshell> a = a.replaceAll(" ", "");
a ==> "abc def"

Also, as shared in the comments, if you want to replace any number of spaces with one space, you can use regex as shared below:

jshell> String a = "abc      def";
a ==> "abc def"

jshell> a = a.replaceAll("\\s+", " ");
a ==> "abc def"

jshell> String a = "abc def";
a ==> "abc def"

jshell> a = a.replaceAll("\\s+", " ");
a ==> "abc def"


Related Topics



Leave a reply



Submit