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)
使用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)
| 归档时间: |
|
| 查看次数: |
4691 次 |
| 最近记录: |