2
\$\begingroup\$

I need to filter an input from a user to never have the have the Pilcrow Sign (¶) character. The following methods filters the input from the user

public String filterInput(String userInput) {
    StringBuilder sBuilder = new StringBuilder();

    for (char character : userInput.toCharArray()) {
        if (checkCharacter(character)) {
            sBuilder.append(character);
        }
    }
    return sBuilder.toString();
}

public boolean checkCharacter(char charToCheck) {
    return charToCheck != 182;
}

filterInput gets passed a String containing the user input which is taken from Scanner(System.in) No previous filtering has been done on the user input.

My concern is, is the code well written or is there still a way for the user to write the Pilcrow sign in such a way that when the String is broken into characters, it could bypass the checkCharacter method and return true, effectively managing to inject the forbidden character in my app?

\$\endgroup\$
2
\$\begingroup\$

Your code looks correct and safe to me. However, I would simplify it as:

public static String filterInput(String userInput) {
    return userInput.replace("\u00b6" /* Pilcrow sign */, "");
}

Two public functions seems like overkill, when all you need is a static function. (If you intend for the filter to be configurable by overriding checkCharacter() in a subclass, then I would suggest changing to a more flexible design where the naughty characters are specified as a parameter.)

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.