7

Could you please let me know is there any way to replace multiple space with single space in java or spring? Any stringUtils function for same?

like

1.

test     test
test test

2.

test  test
test test

3.

test                    test
test test
arshajii
  • 127,459
  • 24
  • 238
  • 287
Adam
  • 727
  • 4
  • 11
  • 21
  • The problem with string utils is they won't replace variable lengths of characters, so you have to default to a single char. But doing this ends up taking a huge amout of time. Better to do this with a regex. –  Sep 16 '13 at 23:36

2 Answers2

28

To replace multiple spaces

output = input.replaceAll("[ ]+", " ");

Or replace multiple whitespace characters (including space, tab, new line, etc.)

output = input.replaceAll("\\s+", " ");
p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
4

This is a variation of @p.s.w.g - it ignores newlines, but still get tabs and such.

output = input.replaceAll("[^\\S\\r\\n]+", " ");