This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Eliminate unnecessary characters from a String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Eliminate unnecessary characters from a String" Watch "Eliminate unnecessary characters from a String" New topic
Author

Eliminate unnecessary characters from a String

Smita Chopra
Ranch Hand

Joined: Jun 27, 2005
Posts: 45
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

Joined: Aug 20, 2001
Posts: 1821

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:



Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
Smita Chopra
Ranch Hand

Joined: Jun 27, 2005
Posts: 45
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

Joined: Dec 06, 2001
Posts: 3061
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


Java API Documentation
The Java Tutorial
 
Consider Paul's rocket mass heater.
 
subject: Eliminate unnecessary characters from a String