出于个人兴趣,我正在标记各种逃避特殊字符的方法。
一位同事建议使用 EnumMap 也可以快速检查字符是否包含在 Map 中。
我正在尝试以下代码,它可以使用containsValue()
;
但是,这可以使用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);
}