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;
}
David
  • 10,418
  • 17
  • 72
  • 122

2 Answers2

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"
C. K. Young
  • 219,335
  • 46
  • 382
  • 435
  • 2
    This is clever... I like this. – Cat Jun 07 '13 at 03:58
  • perfect. thank you. I knew there was a better way than finding the positions of the needle and then using substrings. – David Jun 07 '13 at 04:02
  • @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 `?`). :-) – C. K. Young Jun 07 '13 at 04:03
  • could you edit your answer to show that? i've not worked with replace() or format() before – David Jun 07 '13 at 04:08
  • @David Sure thing. (The `replace` was simply to replace your `?` with `%s`; general usage would not require using `replace`.) – C. K. Young Jun 07 '13 at 04:09
  • Or, you can just pass the `values` array as the second argument. – maybeWeCouldStealAVan Jun 07 '13 at 04:12
  • thanks a ton @Chris. I was still trying to incorporate replace() into and it wasn't working out. Thanks Eric, i'll check that out. – David Jun 07 '13 at 04:12
  • @ChrisJester-Young could you look at my edit? If my values are enclosed in apostrophes the method puts brackets around it. How do i prevent that from happening? – David Jun 08 '13 at 17:45
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);
Edwin Dalorzo
  • 76,803
  • 25
  • 144
  • 205