public static String ReplaceChars(String str) { String ret = str; ret = ret.replaceAll("'","''"); ret = ret.replaceAll("&", "&"); // must call it in first ret = ret.replaceAll("<", "<"); ret = ret.replaceAll(">", ">"); ret = ret.replaceAll("\"", """); return ret; }
public static String Demo(String sSource) {
Pattern p = null; //正则表达式
Matcher m = null; //操作的字符串
String s = null, sTmp = null;
StringBuffer sb = null;
p = Pattern.compile("('|\\"))", Pattern.CASE_INSENSITIVE);
m = p.matcher(sSource);
sb = new StringBuffer();
while (m.find()) {
sTmp = m.group().toLowerCase();
if (sTmp.equals("'"))
s = "'";
else if (sTmp.equals("\""))
s = """ m.appendReplacement(sb, s);
}
m.appendTail(sb);
return sb.toString();
}
防止输入单引号和双引号只是一种防止出错的方法,但如果将其转换为转义字符或许会更好一点...
与楼主一起学习,以下是我找的一段代码://取代全部字串的函數
public String replace(String src, String astr, String bstr) {
int index = 0; StringBuffer sb = new StringBuffer();
do { index = src.indexOf(astr);
if(index == -1) sb.append(src);
else {
sb.append(src.substring(0,index));
sb.append(bstr);
src = src.substring(index + astr.length());
}
} while(index != -1);
return sb.toString();
}JDK 1.4有String.replaceAll( ) 和 String.split() 可以直接置换
但我用的是JDK 1.3
{
String ret = str;
ret = ret.replaceAll("'","''");
ret = ret.replaceAll("&", "&"); // must call it in first
ret = ret.replaceAll("<", "<");
ret = ret.replaceAll(">", ">");
ret = ret.replaceAll("\"", """);
return ret;
}