Java - Including variables within strings?

2019-01-10 16:15发布

Ok, so we all should know that you can include variables into strings by doing:

String string = "A string " + aVariable;

Is there a way to do it like:

String string = "A string {aVariable}";

In other words: Without having to close the quotation marks and adding plus signs. It's very unattractive.

3条回答
放我归山
2楼-- · 2019-01-10 16:39

Also consider java.text.MessageFormat, which uses a related syntax having numeric argument indexes. For example,

String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);

results in string containing the following:

A string of ponies.

More commonly, the class is used for its numeric and temporal formatting. An example of JFreeChart label formatting is described here; the class RCInfo formats a game's status pane.

查看更多
再贱就再见
3楼-- · 2019-01-10 16:45

This is called string interpolation; it doesn't exist as such in Java.

One approach is to use String.format:

String string = String.format("A string %s", aVariable);

Another approach is to use a templating library such as Velocity or FreeMarker.

查看更多
Viruses.
4楼-- · 2019-01-10 16:51

You can always use String.format(....). i.e.,

String string = String.format("A String %s %2d", aStringVar, anIntVar);

I'm not sure if that is attractive enough for you, but it can be quite handy. The syntax is the same as for printf and java.util.Formatter. I've used it much especially if I want to show tabular numeric data.

查看更多
登录 后发表回答