java过滤字符串中的特殊字符

public static String toHtmlString(String str) {
if (str == null || ("").equals(str.trim())) {
return "";
}

StringBuffer stringbuffer = new StringBuffer();
int j = str.length();

for (int i = 0; i < j; i++) {
char c = str.charAt(i);

switch (c) {
case 39: // '
stringbuffer.append("´");
break;
case 60: // <
stringbuffer.append("<");
break;
case 62: // >
stringbuffer.append(">");
break;
case 38: // &
stringbuffer.append("&");
break;
case 34: // "
stringbuffer.append(""");
break;
case 13:
if (i < j - 1 && str.charAt(i + 1) == 10) {
stringbuffer.append("
");
i++;
}
break;
case 32:
stringbuffer.append(" ");
break;
default:
stringbuffer.append(c);
break;
}
}
return new String(stringbuffer.toString());
}

你可能感兴趣的:(java相关)