【发布时间】:2017-10-31 22:33:56
【问题描述】:
我正在尝试使用 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}”
【问题讨论】:
-
this library 怎么样?这是为我自己写的。
标签: java string hashmap substring indexof