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

Dav*_*vid 2 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";
Run Code Online (Sandbox Code Playgroud)

方法签名

public String replaceNeedlesWithValues(String subject, String needle, String[] values){
    //code
    return result;
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*ung 8

使用String.format:

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

:-)

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

String.format("The %s %s was %s his %s", "brown", "dog", "eating", "food");
// => "The brown dog was eating his food"
Run Code Online (Sandbox Code Playgroud)

  • 这很聪明......我喜欢这个. (2认同)