How to including variables within strings?

JavaVariablesInsertIncludeQuotation Marks

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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.

Solution 3 - Java

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.

Solution 4 - Java

Since Java 15, you can use a non-static string method called String::formatted(Object... args)

Example:

String foo = "foo";
String bar = "bar";

String str = "First %s, then %s".formatted(foo, bar);     

Output:

> "First foo, then bar"

Solution 5 - Java

Apache Commons StringSubstitutor can be used.

import org.apache.commons.text.StringSubstitutor;
// ...
Map<String, String> values = new HashMap<>();
values.put("animal", "quick brown fox");
values.put("target", "lazy dog");
StringSubstitutor sub = new StringSubstitutor(values);
String result = sub.replace("The ${animal} jumped over the ${target}.");
// "The quick brown fox jumped over the lazy dog."

This class supports providing default values for variables.

String result = sub.replace("The number is ${undefined.property:-42}.");
// "The number is 42."

To use recursive variable replacement, call setEnableSubstitutionInVariables(true);.

Map<String, String> values = new HashMap<>();
values.put("b", "c");
values.put("ac", "Test");
StringSubstitutor sub = new StringSubstitutor(values);
sub.setEnableSubstitutionInVariables(true);
String result = sub.replace("${a${b}}");
// "Test"

Solution 6 - Java

you can use String format to include variables within strings

i use this code to include 2 variable in string:

> String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGray AdamsView Question on Stackoverflow
Solution 1 - JavaHovercraft Full Of EelsView Answer on Stackoverflow
Solution 2 - JavaJacob MattisonView Answer on Stackoverflow
Solution 3 - JavatrashgodView Answer on Stackoverflow
Solution 4 - JavaDomadinView Answer on Stackoverflow
Solution 5 - JavaUnmitigatedView Answer on Stackoverflow
Solution 6 - JavaalinnView Answer on Stackoverflow