What classes do you use to make string placeholders work?
String template = "You have %1 tickets for %d",
Brr object = new Brr(template, {new Integer(1), new Date()});
object.print();
In the String module, Template Class allows us to create simplified syntax for output specification. The format uses placeholder names formed by $ with valid Python identifiers (alphanumeric characters and underscores).
StringTemplate is a java template engine (with ports for C#, Objective-C, JavaScript, Scala) for generating source code, web pages, emails, or any other formatted text output. Terence Parr is the maniac behind ANTLR and has been working on language tools since 1989.
A template is a String that contains some static text and one or more format specifiers, which indicate which argument is to be placed at the particular position. In this case, there's a single format specifier %s, which gets replaced by the corresponding argument.
You have two options:
java.util.Formatter
printf
-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output.java.text.MessageFormat
.
MessageFormat
provides a means to produce concatenated messages in a language-neutral way. Use this to construct messages displayed for end users. Of the two, MessageFormat
is by far the more powerful. Here's an example of using ChoiceFormat
to handle 0
, 1
, and >1
case differently:
import java.text.MessageFormat;
import java.util.Date;
//...
String p = "You have {0,choice,0#none|1#one ticket|1<{0,number,integer} tickets} for {1,date,full}.";
for (int i = 0; i < 4; i++) {
System.out.println(MessageFormat.format(p, i, new Date()));
}
This prints:
You have none for Tuesday, June 1, 2010.
You have one ticket for Tuesday, June 1, 2010.
You have 2 tickets for Tuesday, June 1, 2010.
You have 3 tickets for Tuesday, June 1, 2010.
The documentation has many more examples.
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