views:

747

answers:

4

Looking for quick, simple way in Java to change this string

" hello     there   "

to something that looks like this

"hello there"

where I replace all those multiple spaces with a single space, except I also want the one or more spaces at the beginning of string to be gone.

Something like this gets me partly there

String mytext = " hello     there   ";
mytext = mytext.replaceAll("( )+", " ");

but not quite.

+4  A: 

You can first use String.trim(), and then apply the regex replace command on the result.

Eyal Schneider
Awesome! I did not think of that. That does the trick.
Nessa
A: 

See String.replaceAll

use the regex /\s/ and replace with " "

then use String.trim

Zak
+3  A: 

To eliminate spaces at the beginning and at the end of the String, use String#trim() method. And then use your mytext.replaceAll("( )+", " ").

folone
+8  A: 

Try this:

String after = before.trim().replaceAll(" +", " ");

See also


No trim() regex

It's also possible to do this with just one replaceAll, but this is much less readable than the trim() solution. Nonetheless, it's provided here just to show what regex can do:

    String[] tests = {
        "  x  ",          // [x]
        "  1   2   3  ",  // [1 2 3]
        "",               // []
        "   ",            // []
    };
    for (String test : tests) {
        System.out.format("[%s]%n",
            test.replaceAll("^ +| +$|( )+", "$1")
        );
    }

There are 3 alternates:

  • ^_+ : any sequence of spaces at the beginning of the string
    • Match and replace with $1, which captures the empty string
  • _+$ : any sequence of spaces at the end of the string
    • Match and replace with $1, which captures the empty string
  • (_)+ : any sequence of spaces that matches none of the above, meaning it's in the middle
    • Match and replace with $1, which captures a single space

See also

polygenelubricants
+1, especially as it's worth noting that doing `trim()` and then `replaceAll()` uses less memory than doing it the other way around. Not by much, but if this gets called many many times, it might add up, especially if there's a lot of "trimmable whitespace". (`Trim()` doesn't really get rid of the extra space - it just hides it by moving the start and end values. The underlying `char[]` remains unchanged.)
glowcoder