File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Remove whitspace completely from a string

 
rastas biggs
Ranch Hand
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know how to replace but how do I remove whitespace completely

 
Saket Barve
Ranch Hand
Posts: 229
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1646
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I get an out of bounds exception, i think cause there is whitespace at the end of the string

 
David Harkness
Ranch Hand
Posts: 1646
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic