aspose file tools*
The moose likes Beginning Java and the fly likes Remove whitspace completely from a string Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Remove whitspace completely from a string" Watch "Remove whitspace completely from a string" New topic
Author

Remove whitspace completely from a string

rastas biggs
Ranch Hand

Joined: Sep 24, 2004
Posts: 41
I know how to replace but how do I remove whitespace completely

Saket Barve
Ranch Hand

Joined: Dec 19, 2002
Posts: 229
Why not use the deleteCharAt( index ) method of StringBuffer?

Alternatively, if you do not wish to disturb the existing object, you can create a new StringBuffer and insert all except for empty characters in this new StringBuffer.

Regards,
Saket
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
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 " +".
rastas biggs
Ranch Hand

Joined: Sep 24, 2004
Posts: 41
I get an out of bounds exception, i think cause there is whitespace at the end of the string

David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Remove whitspace completely from a string