Reputation: 10738
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;
}
Upvotes: 2
Views: 5036
Reputation: 222973
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"
Upvotes: 9
Reputation: 78579
If your string contains patterns that need to be replaced, you can use the appendReplacement method in the Matcher class.
For example:
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);
Upvotes: 1