I need some help improving my code and wondering if I there is a better way to do the following:
StringBuilder buf = new StringBuilder(node.length() + 8);
for (int i=0, n=node.length(); i<n; i++) {
char c = node.charAt(i);
String hexadecimal = "";
switch (c) {
case '"': hexadecimal = "\\22"; break;
case '&': hexadecimal = "\\26"; break;
case '\'': hexadecimal = "\\27"; break;
case '/': hexadecimal = "\\2f"; break;
case ':': hexadecimal = "\\3a"; break;
case '<': hexadecimal = "\\3c"; break;
case '>': hexadecimal = "\\3e"; break;
case '@': hexadecimal ="\\40"; break;
case '\\':hexadecimal = "\\5c"; break;
default: {
if (Character.isWhitespace(c)) {
hexadecimal = "\\20";
}else if(c > 127){
hexadecimal = "\\" + Integer.toHexString(c) + "\\";
}
else {
hexadecimal = String.valueOf(c);
}
}
}
buf.append(hexadecimal);
}
return buf.toString();
I don't like how there is a switch
statement which just sets a variable (hexadecimal
) based on what the case is. I feel there is a better way to do this, such as by using a hash-map. I need the code to be flexible so that adding new characters and setting the hexadecimal is easy.
Integer.toHexString('#')
would get messy. But definitely a good idea. \$\endgroup\$