Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What classes do you use to make string templates?

Tags:

java

string

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();
like image 240
EugeneP Avatar asked Jun 01 '10 08:06

EugeneP


People also ask

Is string a template class?

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).

Is there string template in Java?

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.

What is template string in Java?

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.


1 Answers

You have two options:

  • java.util.Formatter
    • An interpreter for 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.

like image 75
polygenelubricants Avatar answered Nov 14 '22 22:11

polygenelubricants