论坛首页 入门技术论坛

java 替换特殊字符

浏览 5790 次
该帖已经被评为新手帖
作者 正文
   发表时间: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;
           }
       }
    }
  }
有困难,找猪八戒
论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics