2

我将如何用数组中的值替换字符串中的字符或字符串的所有实例?

例如

String testString = "The ? ? was ? his ?";

String[] values = new String[]{"brown", "dog", "eating", "food"};

String needle = "?";

String result = replaceNeedlesWithValues(testString,needle,values);

//result = "The brown dog was eating his food";

方法签名

public String replaceNeedlesWithValues(String subject, String needle, String[] values){
    //code
    return result;
}
4

2 回答 2

8

通过使用String.format

public static String replaceNeedlesWithValues(String subject, String needle, String[] values) {
    return String.format(subject.replace("%", "%%")
                                .replace(needle, "%s"),
                         values);
}

:-)

当然,您可能只想String.format直接使用:

String.format("The %s %s was %s his %s", "brown", "dog", "eating", "food");
// => "The brown dog was eating his food"
于 2013-06-07T03:55:50.943 回答
1

如果您的字符串包含需要替换的模式,您可以使用 Matcher 类中的 appendReplacement 方法。

例如:

StringBuffer sb = new StringBuffer();
String[] tokens = {"first","plane tickets","friends"};
String text = "This is my 1 opportunity to buy 2 for my 3";
Pattern p = Pattern.compile("\\d");
Matcher m = p.matcher(text);
for(int i=0; m.find(); i++) {
    m.appendReplacement(sb, tokens[i]);
}
m.appendTail(sb);
于 2013-06-07T04:07:03.593 回答