我正在尝试使用.format字符串的方法.但是如果我在字符串中放置%1,%2等,则会抛出java.util.UnknownFormatConversionException指向令人困惑的Java源代码段:
private void checkText(String s) {
int idx;
// If there are any '%' in the given string, we got a bad format
// specifier.
if ((idx = s.indexOf('%')) != -1) {
char c = (idx > s.length() - 2 ? '%' : s.charAt(idx + 1));
throw new UnknownFormatConversionException(String.valueOf(c));
}
}
Run Code Online (Sandbox Code Playgroud)
据此我明白,%禁止使用char.如果是这样,那么我应该将什么用于参数占位符?
我使用Scala 2.8.
StringJava中是否有任何替换机制,我可以使用文本传递对象,并在发生时替换字符串.
例如,文本是:
Hello ${user.name},
Welcome to ${site.name}.
Run Code Online (Sandbox Code Playgroud)
我拥有的对象是"user"和"site".我想${}用对象中的等价值替换内部给出的字符串.这与我们替换速度模板中的对象相同.
目前我正在使用org.apache.commons.lang.text.StrSubstitutor:
Map m = ...
substitutor = new StrSubstitutor(m);
result = substitutor.replace(input);
Run Code Online (Sandbox Code Playgroud)
鉴于我想commons-lang从项目中删除依赖项,StrSubstitutor使用标准JRE库的工作和简约实现是什么?
注意:
StrSubstitutor 像这样工作:
Map map = new HashMap();
map.put("animal", "quick brown fox");
map.put("target", "lazy dog");
StrSubstitutor sub = new StrSubstitutor(map);
String resolvedString = sub.replace("The ${animal} jumped over the ${target}.");
Run Code Online (Sandbox Code Playgroud)
屈服于resolveString ="快速的棕色狐狸跳过懒狗."