I would use a boolean[65536] which flags if the character has to be escaped.
I am quite confident that this is faster than the switch.
But only profiling can show if it is really faster.
String query = "http://This+*is||a&&test(whatever!!!!!!)";
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(mustBeEscaped[c]){
queryCharArray[currentIndex++] = '\\';
queryCharArray[currentIndex++] = c;
}
else 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;
}
}
query = new String(queryCharArray,0,currentIndex);
System.out.println("TEST="+query);
private static final boolean[] mustBeEscaped = new boolean[65536];
static{
mustBeEscaped[':']= //
for(char c: "\\?+-!(){}[]^\"~*"[]^\"~*&|".toCharArray()){
mustBeEscaped[c]=true;
}
}