替換佔位符與地圖值我想使用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);
目前,輸出將是 「此設備是$ {狀態}和歸類爲$ {標題}系統」
怎麼樣[這個庫](https://github.com/holi-java/rstring/blob/master/src/test/java/com/holi/RStringVariableReplacementTest.java#L25-L29)?它是爲自己寫的。 –