英文:
if an attribute is not present in map, How to replace the values in template string using strsubsitutor as null or empty string
问题
我有一个字符串
String templateString = "The ${animal} jumps over the ${target}.";
valuesMap.put("animal", "quick brown fox");
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
但是在 valuesMap 中没有 target 属性的条目。
最终的 resolvedString 应该是
The quick brown fox jumps over the ${target}。
而不是 ${target},它应该是空的。模板字符串中没有在映射中找到键的值应该为空或为 null。
所需的结果是
The quick brown fox jumps over the。
如何处理这种情况
英文:
I have a string
String templateString = "The ${animal} jumps over the ${target}.";
valuesMap.put("animal", "quick brown fox");
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
But there is no entry for attr target in valuesMap.
Final resolvedString would be
The quick brown fox jumps over the ${target}.
Instead of ${target}, it need to be empty. Values in templatestring which doesn't have key in map should be empty or null.
required
The quick brown fox jumps over the.
How to handle this
答案1
得分: 1
您的Map<String, String> valuesMap
仅包含键值对"animal", "quick brown fox"
,您需要向映射中添加键值对"target", ""
,操作如下所示:
String templateString = "The ${animal} jumps over the ${target}.";
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", ""); //<-- 将新的键值对添加到映射中
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
英文:
Your Map<String,String> valuesMap
contains just the couple key, value "animal", "quick brown fox"
, you have to add the couple "target", ""
to your map like below:
String templateString = "The ${animal} jumps over the ${target}.";
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", ""); //<-- adding the new couple to the map
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论