CSDN博客

img eric88

处理输入框中输入非法字符的办法,将输入的非法字符转化成合法字符。

发表于2004/10/30 8:29:00  1868人阅读

分类: java

(原创)转贴请标明出处
  /**
  * 将输入字符串中的"/"转化为"//"
  * 将单引号"'"转化为双引号"''"
  * 返回类型:String
  */
 public static String escapeSQLTags(String input) {
  if (input != null) {
//   input = replaceString(input, "//", "////");
   input = replaceString(input, "/'", "/'/'");
  }
  return input;
 }
 /**
  * 将输入的字符串中的"<" ">" "&" """
  * 转化为Html显示的转义字符
  * 返回类型:String
  */
 public static final String escapeHTMLTags(String in) {
  if (in == null) {
   return null;
  }
  char ch;
  int i = 0;
  int last = 0;
  char[] input = in.toCharArray();
  int len = input.length;
  StringBuffer out = new StringBuffer((int) (len * 1.3));
  for (; i < len; i++) {
   ch = input[i];
   if (ch > '>') {
    continue;
   } else if (ch == '<') {
    if (i > last) {
     out.append(input, last, i - last);
    }
    last = i + 1;
    out.append(LT_ENCODE);
   } else if (ch == '>') {
    if (i > last) {
     out.append(input, last, i - last);
    }
    last = i + 1;
    out.append(GT_ENCODE);
   }
  }
  if (last == 0) {
   return in;
  }
  if (i > last) {
   out.append(input, last, i - last);
  }
  return out.toString();
 }

/**
  * 将maiString中的所有oldString替换成newString
  * 返回类型:String
  */
 public static String replaceString(
  String mainString,
  String oldString,
  String newString) {
  if (mainString == null) {
   return null;
  }
  if (oldString == null || oldString.length() == 0) {
   return mainString;
  }
  if (newString == null) {
   newString = "";
  }
  int i = mainString.lastIndexOf(oldString);
  if (i < 0)
   return mainString;
  StringBuffer mainSb = new StringBuffer(mainString);
  while (i >= 0) {
   mainSb.replace(i, i + oldString.length(), newString);
   i = mainString.lastIndexOf(oldString, i - 1);
  }
  return mainSb.toString();
 }
阅读全文
0 0

相关文章推荐

img
取 消
img