150

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

9 Answers 9

391

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.

Sign up to request clarification or add additional context in comments.

9 Comments

@SuhrobSamiev -- String.replaceAll() has been in Java since JDK 1.4. docs.oracle.com/javase/1.4.2/docs/api/java/lang/…, java.lang.String)
I wish I could add more than +1 for the awesome explanation of \s+.
I understood \s+ but what does 2 backslash \\ mean ?
The string literal "\\" represents the string consisting of a single backslash. So to represent \s+ you write "\\s+".
Will this remove carriage return? or would i have to remove "\\r" separately? Thanks!
|
24

You can use the regex

(\s)\1

and

replace it with $1.

Java code:

str = str.replaceAll("(\\s)\\1","$1");

If the input is "foo\t\tbar " you'll get "foo\tbar " as output
But if the input is "foo\t bar" it will remain unchanged because it does not have any consecutive whitespace characters.

If you treat all the whitespace characters(space, vertical tab, horizontal tab, carriage return, form feed, new line) as space then you can use the following regex to replace any number of consecutive white space with a single space:

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

But if you want to replace two consecutive white space with a single space you should do:

str = str.replaceAll("\\s{2}"," ");

Comments

11
String str = "   Text    with    multiple    spaces    ";
str = org.apache.commons.lang3.StringUtils.normalizeSpace(str);
// str = "Text with multiple spaces"

Comments

9

Try this - You have to import java.util.regex.*;

    Pattern pattern = Pattern.compile("\\s+");
    Matcher matcher = pattern.matcher(string);
    boolean check = matcher.find();
    String str = matcher.replaceAll(" ");

Where string is your string on which you need to remove duplicate white spaces

Comments

9

hi the fastest (but not prettiest way) i found is

while (cleantext.indexOf("  ") != -1)
  cleantext = StringUtils.replace(cleantext, "  ", " ");

this is running pretty fast on android in opposite to an regex

3 Comments

Works only for spaces but not other whitespaces such as tabs and newlines.
i know, you have to add more of these while loops for other entities. But this code run much faster on android as these regex, i had to process complete ebooks.
Enormously faster on desktop too. Haven't tested it for a big string, but if you plan on running it on a lot of small strings this is the answer you are looking for.
7

Though it is too late, I have found a better solution (that works for me) that will replace all consecutive same type white spaces with one white space of its type. That is:

   Hello!\n\n\nMy    World  

will be

 Hello!\nMy World 

Notice there are still leading and trailing white spaces. So my complete solution is:

str = str.trim().replaceAll("(\\s)+", "$1"));

Here, trim() replaces all leading and trailing white space strings with "". (\\s) is for capturing \\s (that is white spaces such as ' ', '\n', '\t') in group #1. + sign is for matching 1 or more preceding token. So (\\s)+ can be consecutive characters (1 or more) among any single white space characters (' ', '\n' or '\t'). $1 is for replacing the matching strings with the group #1 string (which only contains 1 white space character) of the matching type (that is the single white space character which has matched). The above solution will change like this:

   Hello!\n\n\nMy    World  

will be

Hello!\nMy World

I have not found my above solution here so I have posted it.

Comments

0

If you want to get rid of all leading and trailing extraneous whitespace then you want to do something like this:

// \\A = Start of input boundary
// \\z = End of input boundary 
string = string.replaceAll("\\A\\s+(.*?)\\s+\\z", "$1");

Then you can remove the duplicates using the other strategies listed here:

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

Comments

0

You can also try using String Tokeniser, for any space, tab, newline, and all. A simple way is,

String s = "Your Text Here";        
StringTokenizer st = new StringTokenizer( s, " " );
while(st.hasMoreTokens())
{
    System.out.print(st.nextToken());
}

Comments

-11

This can be possible in three steps:

  1. Convert the string in to character array (ToCharArray)
  2. Apply for loop on charater array
  3. Then apply string replace function (Replace ("sting you want to replace"," original string"));

1 Comment

That's not a good solution, dropping to a char array doesn't solve anything. You're not actually explaining how to do the replace, which is the core of the problem. Also please do not post completely unrelated links. You'll get flagged as a spammer if you do so.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.