-2

So what i've got is this simple method which should remove all characters except upper and lowercase letters and numbers from a string.

public static String toSimple(String arg) //redurziert einen String auf Buchstaben und ganze Zahlen
{
    String string = arg;
    int i = 0;
    while ( i < string.length())
    {
        if (((int)string.charAt(i) >= 48 && (int)string.charAt(i) <= 57)||((int)string.charAt(i) >= 65 && (int)string.charAt(i) <= 90)||((int)string.charAt(i) >= 97 && (int)string.charAt(i) <= 121))
            i+=1;
        else
        {
            int a = string.length();
            string = string.replaceAll(""+string.charAt(i), "");

            if (!(string.length() < a)) //Just in case
            {
                i+=1;
            }
        }

The problem is that in some cases string.replaceAll won't change anything though reached and given a character. I checked it in the debugger and couldn't find any apparent errors or exceptions. I didn't check the whole ASCII table, I know that the problem will occur for '$' '?' and '.'. Any suggestions how to solve that?

Ahmad F
  • 30,560
  • 17
  • 97
  • 143
  • Note that char literals can be used instead of "magic numbers" - so `(int)string.charAt(i) >= 48` can be written as `string.charAt(i) >= '0'`, which makes it a lot more obvious what you mean. (The cast to `int` isn't necessary in any case). – Andy Turner Nov 08 '16 at 08:03
  • That's a pretty horrible way to remove characters from a String. And it doesn't work. Try the string ",,,+a" - it won't remove the "+". Normally you would build a new String in a StringBuilder but even if you were doing it like this, you'd use `String.substring` twice to get the string before and after the character. – Erwin Bolwidt Nov 08 '16 at 08:05

1 Answers1

2

String.replaceAll takes a regular expression as its first parameter.

$, ? and . are special characters in regular expressions.

Use String.replace instead - this actually uses regular expressions internally too, but it escapes the strings correctly.


However, given that you're using String.replaceAll, you can just use a regular expression to do the whole thing:

return arg.replaceAll("[^A-Za-z0-9]", "");
Andy Turner
  • 137,514
  • 11
  • 162
  • 243