vedi0boy
vedi0boy

Reputation: 1040

Making code to clean string of unwanted characters

I already made all the code for it but I have some issues. Not all the invalid characters are getting removed, I was unable to pickup a pattern though. I've been trying for a long time now to figure out what is causing this and I finally decided to ask you guys to see if someone can figure it out.

Here is the char array of valid characters (All other characters will be removed from string):

static char[] validCharsUsername ={'Q','q','W','w','E','e','R','r','T','t','Y','y','U','u','I','i','O','o','P','p','A','a','S','s','D','d','F','f','G','g','H','h','J','j','K','k','L','l','Z','z','X','x','C','c','V','v','B','b','N','n','M','m','1','2','3','4','5','6','7','8','9','0','_','-'};

Here is the code. (this.validChars is refering to the array):

public String cleanString(String text){
    StringBuilder sb = new StringBuilder(text);
    for(int i = 0;i < sb.length() - 1;i++){
        char character = sb.charAt(i);
        int index = 0;
        char indexChar = this.validChars[0];
        boolean valid = false;
        while(index < this.validChars.length - 1){
            index++;
            indexChar = this.validChars[index];
            if(character == indexChar){
                valid = true;
                index = this.validChars.length;
            }   
        }
        if(!valid){
            if(character == ' '){
                sb.deleteCharAt(i);
                sb.insert(i, '_');
            }else{
                sb.deleteCharAt(i);
            }
            i = 0;
        }
    }
    return sb.toString();
}

Upvotes: 0

Views: 1135

Answers (2)

Pshemo
Pshemo

Reputation: 124265

Maybe consider using regular expressions which. Regex which will match all characters in range a-z and all digits 0-9 can look like [a-zA-Z0-9]. Regex which will match all characters except mentioned earlier can look like [^a-zA-Z0-9] so your code could look like

public String cleanString(String text){
    return text.replaceAll("[^a-zA-Z0-9]","");
}

In case you want also to let spaces or any other characters stay you can add them to this character class and change return statement to text.replaceAll("[^a-zA-Z0-9\\s]",""); (\\s represents whitespaces).

Upvotes: 2

Emran Sadeghi
Emran Sadeghi

Reputation: 612

try use this code :

public static String cleanString(String text){
    StringBuilder sb = new StringBuilder("");
    for(int i = 0;i < text.length();i++){
        for (int j = 0; j < validCharsUsername.length; j++) {
            if (validCharsUsername[j] == text.charAt(i)) {
                sb.append(text.charAt(i));
                break;
            }
        }
    }
    return sb.toString();
}

UPDATE Fist i think it is C# and i wrote C# Code, but now i changed it to java

Upvotes: 1

Related Questions