문제

I'm bench marking various ways to escape special characters, out of personal interest.

A colleague suggested that a EnumMap might also be quick in order to check if a character is contained within the Map.

I'm trying the following code and it works using containsValue();

However, can this be made to work with containsKey();?

public static enum EscapeChars {
        COLON(':'), SLASH('\\'), QUESTION('?'), PLUS('+'), MINUS('-'), EXCLAMATION(
                '!'), LEFT_PARENTHESIS('('), RIGHT_PARENTHESIS(')'), LEFT_CURLY(
                '{'), RIGHT_CURLY('}'), LEFT_SQUARE('['), RIGHT_SQUARE(']'), UP(
                '^'), QUOTE('"'), TILD('~'), ASTERISK('*'),  PIPE('|'),  AMPERSEND('&');

        private final char character;

        EscapeChars(char character) {
            this.character = character;
        }

        public char getCharacter() {
            return character;
        }
    }

    static EnumMap<EscapeChars, Integer> EnumMap = new EnumMap<EscapeChars,Integer>(
            EscapeChars.class);

    static {
        for (EscapeChars ec : EscapeChars.values()) {
        EnumMap.put(ec, (int)ec.character);
        }       
    }

        static void method5_Enum() {

        String query2="";

        for (int j = 0; j < TEST_TIMES; j++) {
            query2 = query;
            char[] queryCharArray = new char[query.length() * 2];
            char c;
            int length = query.length();
            int currentIndex = 0;
            for (int i = 0; i < length; i++) {
                c = query.charAt(i);
                if (EnumMap.containsValue((int)c)) {
                    if ('&' == c || '|' == c) {
                        if (i + 1 < length && query.charAt(i + 1) == c) {
                            queryCharArray[currentIndex++] = '\\';
                            queryCharArray[currentIndex++] = c;
                            queryCharArray[currentIndex++] = c;
                            i++;
                        }
                    } else {
                        queryCharArray[currentIndex++] = '\\';
                        queryCharArray[currentIndex++] = c;
                    }
                } else {
                    queryCharArray[currentIndex++] = c;
                }
            }

            query2 = new String(queryCharArray, 0, currentIndex);
        }


        System.out.println(query2);

    }

Reference: https://softwareengineering.stackexchange.com/questions/212254/optimized-special-character-escaper-vs-matcher-pattern

도움이 되었습니까?

해결책

I don't believe you would want to because you would first have to convert to an EscapeChars which is the point of having a Map for the lookup. I would suggest that given your usage I would use a Map<Integer, EscapeChars> and use containsKey on this map.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top