我有一个字符串The quick * fox jumps * the * dog
,还有一个字符串String[] array = {"brown", "over", "lazy"}
数组。
将数组中的所有*
替换为字符串的最佳方法是什么,然后首先必须将*
替换为array[0]
元素,第二个*
替换为array[1]
等。当然,解决方案必须允许N个元素替换数组中的元素。
发布于 2017-06-10 05:20:31
使用Java库的appendReplacement
功能:
StringBuffer res = new StringBuffer();
Pattern regex = Pattern.compile("[*]");
Matcher matcher = regex.matcher("Quick * fox jumps * the * dog");
int pos = 0;
String[] array = {"brown", "over", "lazy"};
while (matcher.find()) {
String replacement = pos != array.length ? array[pos++] : "*";
matcher.appendReplacement(res, replacement);
}
matcher.appendTail(res);
发布于 2017-06-10 05:19:52
String.format("The quick * fox jumps * the * dog".replace("*", "%s"), array);
> The quick brown fox jumps over the lazy dog
replace
*
to %s
并将String.format
与parameters
一起使用,这种方式是可行的。
见更多信息:如何用Java格式化字符串
发布于 2017-06-10 05:19:26
for (String x : array) {
yourString = yourString.replaceFirst("\\*", x);
}
https://stackoverflow.com/questions/44473691
复制