在字符串中的特定索引处替换字符串?
问题描述:
我们如何替换Java中现有字符串中的特定字符串?在字符串中的特定索引处替换字符串?
例子:
String param = "aa,bb,cc";
String str =
"select column_val from table_name where a = '?' and b = '?' and c = '?'";
现在我想取代它的地位就像PARAMS ..
String newStr =
"select column_val from table_name where a = 'aa' and b = 'bb' and c = 'cc'";
我们怎样才能做到这一点?是否有任何现有的方法在stringutil或有任何方法来做到这一点?
答
我建议你使用StringBuilder。它们在你的字符串操作类型中提供了一些性能增益,特别是如果你的sql或params是长字符串。
下面是一个例子:
String param = "aa,bb,cc";
String str =
"select column_val from table_name where a = '?' and b = '?' and c = '?'";
@Test
public void Substitute(){
StringBuilder builder=new StringBuilder(str);
String[] params = param.split(",");
int position=0;
for (String paramValue:params){
position=builder.indexOf("?",position);
if (position==-1)
throw new RuntimeException("too parameter values specified.");
builder.replace(position,position+1,paramValue);
position++;
}
position=str.indexOf("?",position);
if (position!=-1)
throw new RuntimeException("Not all parameter specified.");
Assert.assertEquals(builder.toString(),
"select column_val from table_name where a = 'aa' and b = 'bb' and c = 'cc'");
}
正如其他人所说,要记得消毒PARAM值,以避免安全问题......
答
正确的处理方法是usingPreparedStatement
。它不仅会替代你,它还会防止你对抗SQL injection attacks。
是的,我只是证明这里选择查询,但它不是选择查询,这是简单的字符串
在这种情况下,有一个简单的方法来做到这一点:
String param = "aa,bb,cc";
String str = "select column_val from table_name where a = '?' and b = '?' and c = '?'";
String fmt = str.replaceAll("[?]", "%s");
String newStr = String.format(fmt, (Object[])param.split(","));
确保您输入的模式没有任何杂散的问号或百分号字符。
答
String param = "aa,bb,cc";
String str =
"select column_val from table_name where a = # and b = # and c = #";
String [] arr = param.split(",");
for(int i=0; i<arr.length; i++){str.indexOf("#");
str = str.replaceFirst("#", "'"+arr[i]+"'");
}
System.out.println(str);
你考虑使用事先准备好的声明,而不是编辑查询? – triclosan