File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Deleting Characters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Deleting Characters" Watch "Deleting Characters" New topic

Deleting Characters

Allen Thomas

Joined: Jul 02, 2002
Posts: 29
Would anyone know how to check for special characters (excluding some of the characters) in a String? For example: The String I am parsing is 1. MAINT & SVC*-7?8 and I want to find all the characters that I want to delete (see code below) and not have to right a huge case statement. Is there any already made java method that would check for special characters? So the sample string I want to keep the '.' and the '?'.
Keep in mind that the string could also contain many other characters that are accepted and not accepted.
Here is my code:

Thanks for your help.
[ August 15, 2002: Message edited by: Jim Yingst ]
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Well, I guess it really depends what you mean by "special". The Character class has some methods you might find useful, like isLetter(), isNumber(), etc - using these may be shorter than listing all the letters/numbers/whatever. Or for a much more powerful and flexible toolset, check out the java.util.regex package. You can probably find a whole different way to approach the problem there.
If you do get stuck writing a case statement, it needn't be that bad. You've already got a fair amount of needless duplication in your code. For example if two different characters are processed the same way, you don't need to make separate case blocks for them - you can put them together, like # and & below:

Also, I'm guessing deleteCharacter is going to be a horribly inefficient method that creates a whole new String every time you want to delete a character. A smoother approach might be to create a StringBuffer. Instead of deleteing certain characters, you write your method to write all the other characters to the buffer. Then when you're done, use toString() to extract the boffer contents:

I have no idea what you're trying to do with the indexes, so I left them alone. But I suspect you're going to cause an infinite loop if you're not careful, so consider what you want to do here carefully. Good luck...
[ August 20, 2002: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister
John Dale
Ranch Hand

Joined: Feb 22, 2001
Posts: 399
Is this what you want done?
Allen Thomas

Joined: Jul 02, 2002
Posts: 29
Jim and John
Thank you so much for your great advice and help. I implemented both of your techniques in some capacity.
I agree. Here's the link:
subject: Deleting Characters
It's not a secret anymore!