浏览 5790 次
锁定老帖子 主题:java 替换特殊字符
该帖已经被评为新手帖
|
|
---|---|
作者 | 正文 |
发表时间:2007-02-05
最后修改:2009-08-19
有困难,找猪八戒
/** Given a string, this method replaces all occurrences of * '<' with '<', all occurrences of '>' with * '>', and (to handle cases that occur inside attribute * values), all occurrences of double quotes with * '"' and all occurrences of '&' with '&'. * Without such filtering, an arbitrary string * could not safely be inserted in a Web page. */ public static String filter(String input) { if(!hasSpecialChars(input)){ return(input); } StringBuffer filtered = new StringBuffer(input.length()); char c; for(int i=0; i<input.length(); i++) { c = input.charAt(i); if (c == '<') { filtered.append("<"); } else if (c == '>') { filtered.append(">"); } else if (c == '"') { filtered.append("""); } else if (c == '&') { filtered.append("&"); } else { filtered.append(c); } } return(filtered.toString()); } public static boolean hasSpecialChars(String input) { boolean flag = false; if((input !=null) && (input.length()>0)) { char c; for(int i=0; i<input.length();i++) { c = input.charAt(i); switch(c) { case '<': flag = true; break; case '>': flag = true; break; case '"': flag = true; break; case '&': flag = true; break; } } } } 有困难,找猪八戒 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |