【问题标题】:java how replace a char at a set index with a string [closed]java如何用字符串替换设置索引处的字符[关闭]
【发布时间】:2013-10-26 13:26:31
【问题描述】:

您好,我需要能够用设置索引处的字符串替换一个字符。

例子:

"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);
}
}

【问题讨论】:

  • 是用于sql查询吗?!在这种情况下,您可以使用PreparedStatement
  • 你试过了吗?
  • 试着改变你的问题,问你真正想要什么。避免XY problem
  • 我正在为自定义数据库系统构建自己的查询机制,所以没有使用 mysql,因此preparedstatement 不符合我的需求
  • 请不要将答案放在问题中。您可以添加自己的答案,也可以接受可以解决您问题的现有答案。

标签: java string replace char


【解决方案1】:

这会将您的输入字符串转换为所需的输出:

str = String.format(str.replace("?", "%s"), "Mr Boo", "cake", "Mr Foo");

【讨论】:

    【解决方案2】:

    您可以使用Mapregex 来实现此功能,如下所示:

    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
    

    【讨论】:

    • 感谢您的帮助,我使用了您的代码并已经完成了我的回答。
    • @user2716281 如果您使用此答案,那么除了说“谢谢”之外,您还应该accept it
    • @user2716281 没那么快。我没有意识到如果你这样做,例如map.put(0, "What happened?"),那么这个方法就不能正常工作。请参阅修复此错误的更新答案。
    【解决方案3】:

    如果您有一种方法可以在字符串中找到第 n 个? 并将其替换为单词,那么主要问题是。例如第二个?(id = 1)你将被“蛋糕”替换,当你想赶上第三个?(id = 2)时,由于第二个?已经被蛋糕替换了,这将是现在“新”第二而不是第三。

    因此,最好的方法是将? 的查询拆分为String Array,使其成为static,如果你想绑定id = 1,选择array[1] 并附加你想要的字符串,如果你想要 id=n 选择 array[n] 并附加你的字符串..

    最后,追加数组的所有元素,查询就完成了。

    类似

    static String[] arrayQuery =  "hello ? would you like a ? from ?".split("?");
    
    public void fillQuery(int position, String word) {
       arrayQuery[position] = arrayQuery[position]+word);
    }
    

    最后,要返回查询,遍历数组并返回一个包含所有元素的String

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 1970-01-01
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多