Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Eliminate unnecessary characters from a String

 
Smita Chopra
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a method which accepts a String and after eliminating some unnecessary characters like @,* etc it returns the String.

I have not been able to totally eliminate the not allowed characters, but have managed to replace them with a $ sign.
Can someone please tell me how to eliminate the uneeded characters.


[ July 29, 2005: Message edited by: Smita Chopra ]
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Perhaps the String.replaceAll() method is what you want. It takes a regular expression and replaces all occurrances of the regular expression with the substitute value.



This replaces all occuranecs of @, %, ., and * with the empty string, thereby eliminating them from your string.

Your way could work, albeit much less efficiently, with simply elimating the characters instead of replacing them with a dollar sign, akin to:

 
Smita Chopra
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Joel McNary:
Perhaps the String.replaceAll() method is what you want. It takes a regular expression and replaces all occurrances of the regular expression with the substitute value.



This replaces all occuranecs of @, %, ., and * with the empty string, thereby eliminating them from your string.

Your way could work, albeit much less efficiently, with simply elimating the characters instead of replacing them with a dollar sign, akin to:



Thanks a lot. It was much easier than I thought
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As mentioned the Java API contains a lot of helpful tools to simplify common tasks like this. However, as a learning exercise, sometimes it's good to implement it yourself as you tried in your original approach. If you are interested in fixing your original code, you may want to look at the StringBuffer or StringBuilder (in Java 1.5) classes. Since String is immutable, these classes allow you to dynamically build a String from other Strings or primitives.

HTH

Layne
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic