jdk1.3及以下版本就自己定义一个replace方法,如下: public String replace(String parentStr,String ch,String rep) { int i = parentStr.indexOf(ch); StringBuffer sb = new StringBuffer(); if (i == -1) return parentStr; sb.append(parentStr.substring(0,i) + rep); if (i+ch.length() < parentStr.length()) sb.append(replace(parentStr.substring(i+ch.length(),parentStr.length()),ch,rep)); return sb.toString(); } 调用: String s="test String=? and test String =? and test String =?"; s=replaceAll(s,"?","!");
谢谢,,我不想那么替换的,想这样的,最后的结构是 String s="test String=1 and test String =2 and test String =3";
只能自己写函数了,java中是在SQL语句中有这种功能
public void test () { String sql = "select * from groupform where groupid=? order=? by desc"; String[] array = {"1","2"}; System.out.println(constructSql(sql,array)); } public static String constructSql (String sql,String[] array) { String key = "\\?"; Pattern p = Pattern.compile(key); Matcher m = p.matcher(sql); StringBuffer stringBuffer = new StringBuffer(); int i = 0; boolean result = m.find(); while (result) { m.appendReplacement(stringBuffer,array[i]); result = m.find(); i ++; } return String.valueOf(m.appendTail(stringBuffer)); }
public String replace(String parentStr,String ch,String rep) {
int i = parentStr.indexOf(ch);
StringBuffer sb = new StringBuffer();
if (i == -1)
return parentStr;
sb.append(parentStr.substring(0,i) + rep);
if (i+ch.length() < parentStr.length())
sb.append(replace(parentStr.substring(i+ch.length(),parentStr.length()),ch,rep));
return sb.toString();
}
调用:
String s="test String=? and test String =? and test String =?";
s=replaceAll(s,"?","!");
String s="test String=1 and test String =2 and test String =3";
String sql = "select * from groupform where groupid=? order=? by desc";
String[] array = {"1","2"};
System.out.println(constructSql(sql,array));
}
public static String constructSql (String sql,String[] array) {
String key = "\\?";
Pattern p = Pattern.compile(key);
Matcher m = p.matcher(sql);
StringBuffer stringBuffer = new StringBuffer();
int i = 0;
boolean result = m.find();
while (result) {
m.appendReplacement(stringBuffer,array[i]);
result = m.find();
i ++;
}
return String.valueOf(m.appendTail(stringBuffer));
}