tags:

views:

220

answers:

5

How do I trim spaces inside leaving only one space taking consideration of performance?

Input:
     AA     BB
Output:
AA BB

Input:
A      A
Output:
A A
+6  A: 

Replace two or more spaces "\\s{2,}" by a single space " " and do a trim() afterwards to get rid of the leading and trailing spaces as you showed in the 1st example.

output = input.replaceAll("\\s{2,}", " ").trim();
BalusC
A: 

"Hello a a g g a   gag gs    gs@".replaceAll( "[ ]+{2}", " ") ).trim();

William
+7  A: 
System.out.println("     AA     BB".replaceAll("\\s+", " ").trim());

Output:

AA BB

Note: Unlike some of the other solutions here, this also replaces a single tab with a single space. If you don't have any tabs you can use " {2,}" instead which will be even faster:

System.out.println("     AA     BB".replaceAll(" {2,}", " ").trim());
Mark Byers
Thanks a bunch.. :)
Alex Gomes
+1  A: 
s = s.replaceAll("\\s+", " " ).trim();
peter.murray.rust
A: 

There are correct answers here, e.g.:

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

But I think it's also important to choose the correct question. Instead of asking about trimming a String using regular expressions, why not just ask about trimming the String, and allow people answering to show you the best strategy?

There may well be better ways to collapse spaces than to use a regular expression. There are certainly other ways.

roryparle
The question has been edited. Now could you please show me a better way? Thanks.
Alex Gomes
I didn't mean to imply that there was an indisputably better way. If I knew one I would certainly have told you without insisting the question be changed first. I just wanted to point out that it was possible that you were limiting responses based on an assumption of the correct strategy. I would say that unless you have very strong performance reasons to want to experiment with alternatives, the regex route is probably what I would do.
roryparle
Banging my head..lol
Alex Gomes