java - 使用 indexOf 将占位符替换为 Map 值

标签 java string hashmap substring indexof

我正在尝试使用indexOf 来查找字符串中的占位符(“${...}”)。 到目前为止,我下面的小例子运行良好,但显然仅适用于第一次出现。我如何更改此代码才能遍历所有占位符并最终重建字符串。输入字符串可以是随机的,并且其中没有固定数量的占位符。不太确定从这里去哪里。

// example Hashmap
HashMap <String, String> placeHolderMap = new HashMap<String, String>();
placeHolderMap.put("name", "device");
placeHolderMap.put("status", "broken");
placeHolderMap.put("title", "smartphone");

// input String
String content = "This ${name} is ${status} and categorized as ${title} in the system";
int left = content.indexOf("${");
int right = content.indexOf("}");

// getting the name of the placeholder, if the placeholdermap contains the placeholder as a key it sets the placeholder to the corresponding value
String contentPlaceHolder = content.substring(left+2, right);
if (placeHolderMap.containsKey(contentPlaceHolder)){
    contentPlaceHolder = placeHolderMap.get(contentPlaceHolder);
}
content = content.substring(0, left) + contentPlaceHolder + content.substring(right+1);

目前,输出为“此设备为 ${status},在系统中分类为 ${title}”

最佳答案

为什么不使用 String.replaceAll() 方法?

    Map<String, String> placeHolderMap = new HashMap<>();
    placeHolderMap.put("\\$\\{name}", "device");
    placeHolderMap.put("\\$\\{status}", "broken");
    placeHolderMap.put("\\$\\{title}", "smartphone");


    // input String
    String content = "This ${name} is ${status} and categorized as ${title} in the system";

    for (Map.Entry<String, String> entry : placeHolderMap.entrySet()) {
          content = content.replaceAll(entry.getKey(), entry.getValue());
    }

更新Stefan、Neil 和 Kennet,谢谢。

更新 2017 年 7 月 17 日 您还可以使用不使用正则表达式的 String.replace() 方法,或者使用 Pattern.quote() 方法:

    Map<String, String> placeHolderMap = new HashMap<>();
    placeHolderMap.put("${name}", "device");
    placeHolderMap.put("${status}", "broken");
    placeHolderMap.put("${title}", "smartphone");


    // input String
    String content = "This ${name} is ${status} and categorized as ${title} in the system";

    for (Map.Entry<String, String> entry : placeHolderMap.entrySet()) {
          content = content.replace(entry.getKey(), entry.getValue());
          // content = content.replaceAll(Pattern.quote(entry.getKey()), entry.getValue());
    }

关于java - 使用 indexOf 将占位符替换为 Map 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44279378/

相关文章:

java - 为什么HashMap的N个条目和HashSet的N个条目在堆中占用相同的空间?

具有完整 URI 和方案的 Java httpClient 4.3.6 基本身份验证

java - 如何在集群上使用 JVM 程序? (比如停产的 cJVM/JavaSplit)

java - 将一些 HashMap 键/值映射到 POJO

PHP 字符串连接和换行

string - 为什么在Golang中使用逗号和下划线。解释以下代码中的第12行?

java - 测试/分析 java hashmap 的 hashcode 函数

java - JVM 的 "-server"选项是否需要成为第一个选项?

c - 为什么指针算术在 char* 函数中不起作用

ruby - 如何从参数数组中检索 Ruby/Sinatra 参数?