用数组值替换字符串中的字符实例

时间:2013-06-07 03:52:41

标签: java arrays string

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

例如

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;
}

2 个答案:

答案 0 :(得分: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"

答案 1 :(得分: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);