问题
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.
回答1:
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.
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/9643610/java-including-variables-within-strings