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
Convert JSON String to Pretty Print JSON Output Using Jackson
How to Subtract X Day from a Date Object in Java
Printing Java Collections Nicely (Tostring Doesn't Return Pretty Output)
Java Lambda Stream Distinct() on Arbitrary Key
Calling Outer Class Function from Inner Class
Run Single Test from a Junit Class Using Command-Line
Can You Split a Stream into Two Streams
List All Files from a Directory Recursively with Java
Why Can't Enum's Constructor Access Static Fields
Correct Way to Close Nested Streams and Writers in Java
Communication Between Two Separate Java Desktop Applications
How to Extract Cn from X509Certificate in Java
Java: How to Compile an Entire Directory Structure of Code
Jackson Renames Primitive Boolean Field by Removing 'Is'
Performance Differences Between Arraylist and Linkedlist
"Unable to Acquire Application Service" Error While Launching Eclipse
Noclassdeffounderror in Java: Com/Google/Common/Base/Function