I'm looking for something to achieve the following:
String s = "hello {}!"; s = generate(s, new Object[]{ "world" }); assertEquals(s, "hello world!"); // should be true
I could write it myself, but It seems to me that I saw a library once which did this, probably it was the slf4j logger, but i don't want to write log messages. I just want to generate strings.
Do you know about a library which does this?
printf("%d %d", 42, 23); We've put two %d symbols in the template String. These two symbols represent placeholders for a certain type of value. For instance, the %d is a placeholder for a decimal numeric value.
A Placeholder is a predefined location in a JSP that displays a single piece of web content at a time that is dynamically retrieved from the BEA Virtual Content Repository.
See String.format
method.
String s = "hello %s!"; s = String.format(s, "world"); assertEquals(s, "hello world!"); // should be true
StrSubstitutor
from Apache Commons Lang may be used for string formatting with named placeholders:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-text</artifactId> <version>1.1</version> </dependency>
https://commons.apache.org/proper/commons-lang/javadocs/api-3.4/org/apache/commons/lang3/text/StrSubstitutor.html :
Substitutes variables within a string by values.
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:
String template = "Hi ${name}! Your number is ${number}"; Map<String, String> data = new HashMap<String, String>(); data.put("name", "John"); data.put("number", "1"); String formattedString = StrSubstitutor.replace(template, data);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With