How would i go about replacing all instances of a character or string within a string with values from an array?
For example
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";
method signature
public String replaceNeedlesWithValues(String subject, String needle, String[] values){
//code
return result;
}
By using String.format:
public static String replaceNeedlesWithValues(String subject, String needle, String[] values) {
return String.format(subject.replace("%", "%%")
.replace(needle, "%s"),
values);
}
:-)
Of course, you'll probably just want to work with String.format directly:
String.format("The %s %s was %s his %s", "brown", "dog", "eating", "food");
// => "The brown dog was eating his food"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With