2

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;
}
3
  • //code (..for you to attempt) Commented Jun 7, 2013 at 3:55
  • I'd give this a shot stackoverflow.com/questions/3695230/… Commented Jun 7, 2013 at 3:56
  • nope. not homework. I could attempt to write something that uses a lot of substrings but i know there's a more efficient way to go about doing this. Commented Jun 7, 2013 at 3:59

2 Answers 2

9

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"
Sign up to request clarification or add additional context in comments.

8 Comments

This is clever... I like this.
perfect. thank you. I knew there was a better way than finding the positions of the needle and then using substrings.
@David Of course, but this also illustrates that you'd be far better off using String.format directly in your code (use %s as your placeholders rather than ?). :-)
could you edit your answer to show that? i've not worked with replace() or format() before
@David Sure thing. (The replace was simply to replace your ? with %s; general usage would not require using replace.)
|
1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.