StringSubstitutor from Apache Commons Text library is a lightweight way of doing this, provided your values are already formatted correctly.
Map<String, String> values = new HashMap<>();
values.put("value", "1");
values.put("column","2");
StringSubstitutor sub = new StringSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");
The result string will contain the following:
There's an incorrect value '1' in column # 2
When using Maven you can add this dependency to your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
Answer from schup on Stack OverflowStringSubstitutor from Apache Commons Text library is a lightweight way of doing this, provided your values are already formatted correctly.
Map<String, String> values = new HashMap<>();
values.put("value", "1");
values.put("column","2");
StringSubstitutor sub = new StringSubstitutor(values, "%(", ")");
String result = sub.replace("There's an incorrect value '%(value)' in column # %(column)");
The result string will contain the following:
There's an incorrect value '1' in column # 2
When using Maven you can add this dependency to your pom.xml:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-text</artifactId>
<version>1.10.0</version>
</dependency>
not quite, but you can use MessageFormat to reference one value multiple times:
MessageFormat.format("There's an incorrect value \"{0}\" in column # {1}", x, y);
The above can be done with String.format() as well, but I find messageFormat syntax cleaner if you need to build complex expressions, plus you dont need to care about the type of the object you are putting into the string
Java string templatizer / formatter with named arguments - Stack Overflow
A simple string formatter that supports named arguments and limited "object introspection" at the template level.
Am i only one who does not quite like this? :)
Usually with similar helpers you got the part "How" and then next "What". Imho mixing them together is only asking for troubles
More on reddit.comjava - How to format message with argument names instead of numbers? - Stack Overflow
String template with named placeholders
You can use MapFormat for this. Find out the details here:
http://www.java2s.com/Code/Java/I18N/AtextformatsimilartoMessageFormatbutusingstringratherthannumerickeys.htm
String text = "The user {name} has email address {email}.";
Map map = new HashMap();
map.put("name", "Robert");
map.put("email", "rhume55@gmail.com");
System.out.println("1st : " + MapFormat.format(text, map));
OUTPUT:
1st : The user Robert has email address rhume55@gmail.com.
See StrSubstitutor from org.apache.commons.lang3:
Map valuesMap = HashMap();
valuesMap.put("animal", "quick brown fox");
valuesMap.put("target", "lazy dog");
String templateString = "The ${animal} jumped over the ${target}.";
StrSubstitutor sub = new StrSubstitutor(valuesMap);
String resolvedString = sub.replace(templateString);
// resolvedString: "The quick brown fox jumped over the lazy dog."
Imagine the following piece of code
Template("Hello {name}, you are {position} in line").format(name="Alice", position=12, extra=42)
Would you rather that an error be thrown due to an unbound key (extra) being passed or should it be ignored?
I didn't find much languages even having such string templating built in except other than Python (string.format) and Rust (format!), in Python the extra key/value is ignored, while Rust will throw an exception.
What would be your approach?
String.format()
Since Java 5, you can use String.format to parametrize Strings. Example:
String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
floatVar, intVar, stringVar);
See http://docs.oracle.com/javase/tutorial/java/data/strings.html
Alternatively, you could just create a wrapper for the String to do something more fancy.
MessageFormat
Per the comment by Max and answer by Affe, you can localize your parameterized String with the MessageFormat class.
You could use String.format. Something like:
String message = String.format("You requested %2$s but were assigned %1$s", "foo", "bar");
will generate
"You requested bar but were assigned foo"