嗨,我需要能够用设置索引处的字符串替换一个字符。
例子:
"hello ? would you like a ? from ?"
这是我想使用的方法:
query.bindValue(0,"Mr Boo");
query.bindValue(1,"cake");
query.bindValue(2,"Mr Foo");
我想要的输出:
"hello Mr Boo would you like a cake from Mr Foo"
我需要把它按任何顺序排列,结果是一样的:
query.bindValue(2,"Mr Foo");
query.bindValue(0,"Mr Boo");
query.bindValue(1,"cake");
回答:
public class DBQuery {
private String querystr;
Map<Integer,String> map = new HashMap<>();
public void prepare(String str){
this.querystr = str;
}
public void bindValue(int num, String value){
map.put(num, value);
}
public void execute(){
java.util.List<Integer> keys = new ArrayList<>(map.keySet());
Collections.sort(keys);
for(Integer key : keys){
querystr = querystr.replaceFirst("\\?", map.get(key));
}
System.out.println(querystr);
}
}