I\'m looking for something to achieve the following:
String s = \"hello {}!\";
s = generate(s, new Object[]{ \"world\" });
assertEquals(s, \"hello world!\");
Justas answer is outdated so I'm posting up to date answer with apache text commons.
StringSubstitutor
from Apache Commons Text may be used for string formatting with named placeholders:
https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringSubstitutor.html
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.9</version>
</dependency>
This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is ${variableName}. The prefix and suffix can be changed via constructors and set methods. Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying a custom variable resolver.
Example:
// Build map
Map<String, String> valuesMap = new HashMap<>();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
// Build StringSubstitutor
StringSubstitutor sub = new StringSubstitutor(valuesMap);
// Replace
String resolvedString = sub.replace(templateString);
This can be done in a single line without the use of library. Please check java.text.MessageFormat
class.
Example
String stringWithPlaceHolder = "test String with placeholders {0} {1} {2} {3}";
String formattedStrin = java.text.MessageFormat.format(stringWithPlaceHolder, "place-holder-1", "place-holder-2", "place-holder-3", "place-holder-4");
Output will be
test String with placeholders place-holder-1 place-holder-2 place-holder-3 place-holder-4