Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace instances of character in a string with array values

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;
}
like image 841
David Avatar asked Feb 26 '26 20:02

David


1 Answers

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"
like image 137
Chris Jester-Young Avatar answered Mar 01 '26 08:03

Chris Jester-Young