You can modify your existing code by only inserting the char c if it isn't whitespace. Note that a char variable is always a valid character, and '' is not a valid character, thus the compiler error.
If you're using JDK 1.4 or later, you can replace the entire thing withThe regular expression "\s+" matches one or more whitespace characters: [ \t\n\x0B\f\r]. If you want to remove only spaces, change "\s+" to " +".
Joined: Sep 24, 2004
I get an out of bounds exception, i think cause there is whitespace at the end of the string
Joined: Aug 07, 2003
No, you get an out of bounds exception because you're not editing an existing StringBuffer. Instead, you're adding each character from the original String to the end of it. I think Saket assumed you had started by putting the String into the StringBuffer and were removing the whitespace characters as you scanned it.
See my earlier post, though.
subject: Remove whitspace completely from a string