Removing certain characters from a string

前端 未结 8 1464
清酒与你
清酒与你 2020-12-05 10:46

I am thinking about using String.replaceAll() to remove certain characters in my string. It is unclear which characters are going to be removed (i.e. which char

8条回答
  •  旧时难觅i
    2020-12-05 11:34

    This is one of those cases where regular expressions are probably not a good idea. You're going to end up writing more special code to get around regex than if you just take the simple approach and iterate over the characters. You also risk overlooking some cases that might surface as a bug later.

    If you're concerned about performance, regex is actually going to be much slower. If you look through the code or profile the use of it, regex has to create a pattern to parse/compile, run through the matching logic and then apply your replacement. All of that creates a lot of objects, which can be expensive if you iterate on this frequently enough.

    I'd implement what you found on that link a little differently though. You can save on unnecessary String allocations as it builds the result without any additional complexity:

    public static String stripChars(String input, String strip) {
        StringBuilder result = new StringBuilder();
        for (char c : input.toCharArray()) {
            if (strip.indexOf(c) == -1) {
                result.append(c);
            }
        }
        return result.toString();
    }
    

提交回复
热议问题