【发布时间】:2021-03-26 08:29:30
【问题描述】:
我在 Java 中有一个字符串,其中包含许多模式。有一个值数组需要根据顺序替换字符串中的每个模式。下面是该方法应该做什么的示例。
public static String replaceValues(String withPattern, String... params){
Matcher matcher = Pattern.compile("\\{\\}").matcher(withPattern);
StringBuffer sb = new StringBuffer();
int index =0;
while (matcher.find()) {
if (args.length == index) {
matcher.appendTail(sb);
return sb.toString();
}
matcher.appendReplacement(sb, params[index]);
index++;
}
return sb.toString();
}
// A quick brown fox jumps over the lazy dog.
replaceValues("A quick brown {} jumps over the lazy {}", "fox", "dog");
这行得通。我只是想知道是否有一种更有效的方式来编写这段代码,而不是过于声明。
【问题讨论】:
-
数组
values在哪里定义?