1

so I have been looking on here and I can find alot of solutions that either completely remove all white space or just remove spaces, or just remove tabs. Basically what I need/ want is a way to take a string, and turn all double spaces+ or tabs and turn them into a single space. ie

String temp = "This is   a     test        for strings";
String result = "This is a test for strings";

any ideas? possible java library methods?

M A
  • 71,713
  • 13
  • 134
  • 174

3 Answers3

4

Use String.replaceAll:

String result = temp.replaceAll("\\s+", " ");

where \\s+ stands for more than one whitespace character.

M A
  • 71,713
  • 13
  • 134
  • 174
2

You can use regExp with method #replaceAll other than that you can first use trim to remove leading and trailing spaces.

    String temp = "This is   a     test        for strings";
    String result = temp.replaceAll("\\s+", " ");

Here \\s+ is regExp which means one or more spaces which will be replaced with single space by replaceAll method.

akash
  • 22,664
  • 11
  • 59
  • 87
1

Try this:

String temp = "This is   a     test        for strings";
String result = temp.replaceAll("\\s+", " "));
Krayo
  • 2,492
  • 4
  • 27
  • 45