java如何用字符串替换集合索引中的字符
嗨,我需要能够在一组索引中用字符串替换一个字符 例如:java如何用字符串替换集合索引中的字符,java,string,replace,char,Java,String,Replace,Char,嗨,我需要能够在一组索引中用字符串替换一个字符 例如: "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.bindVa
"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);
}
}
如果你有一个找到第n个的方法,主要的问题是什么?在一个字符串中,用一个单词来回答它。比如二号?id=1您将用蛋糕代替,何时您想赶上第三个?id=2,从2号开始?已经被蛋糕取代,这将是新的第二个而不是第三个 因此,最好的方法是按?在字符串数组中,将其设为静态,如果要执行绑定id=1,请选择数组[1]并附加所需的字符串,如果需要id=n,请选择数组[n]并附加字符串 最后,追加数组的所有元素,查询就完成了 差不多
static String[] arrayQuery = "hello ? would you like a ? from ?".split("?");
public void fillQuery(int position, String word) {
arrayQuery[position] = arrayQuery[position]+word);
}
最后,要返回查询,请遍历数组并返回一个包含所有元素的字符串,这将把输入字符串转换为所需的输出:
str = String.format(str.replace("?", "%s"), "Mr Boo", "cake", "Mr Foo");
您可以使用Map和regex实现此功能,如下所示:
Map<Integer,String> map = new HashMap<>(); //this map contains the values
map.put(3, "Mr Foo");
map.put(0, "Mr Boo");
map.put(1, "cake");
map.put(2, "cookie");
String query = "hello ? would you like a ? or a ? from ?"; //this is the query
Matcher matcher = Pattern.compile("\\?").matcher(query);
int index = 0;
StringBuffer sb = new StringBuffer();
while(matcher.find()){
matcher.appendReplacement(sb, map.get(index));
index++;
}
matcher.appendTail(sb);
System.out.println(sb.toString()); // this will display the query as you want
它是用于sql查询的吗?!在这种情况下,你可以使用PreparedStatement。你已经试过了吗?试着改变你的问题,问你真正想要什么。避免我正在为自定义数据库系统构建自己的查询机制,因此我不使用mysql,因此preparedstatement不适合我的需要请不要在问题中给出答案。您可以添加自己的答案,也可以接受解决问题的现有答案。谢谢您的帮助,我使用了您的代码,并且已经完成了我的答案。@user2716281如果您正在使用此答案,那么除了说“谢谢您也应该”之外。@user2716281不要太快。我不知道如果你做了例如map.put0,发生了什么?那么这个方法就不能正常工作了。请参阅修复此错误的更新答案。