143

因此,我们都应该知道,您可以通过以下方式将变量包含到字符串中:

String string = "A string " + aVariable;

有没有办法做到这一点:

String string = "A string {aVariable}";

换句话说:无需关闭引号并添加加号。这很没有吸引力。

4

6 回答 6

154

您始终可以使用 String.format(....)。IE,

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

我不确定这对你是否足够有吸引力,但它可能非常方便。语法与 printf 和 java.util.Formatter 的语法相同。我经常使用它,特别是如果我想显示表格数字数据。

于 2012-03-10T03:12:48.677 回答
82

这称为字符串插值;它在 Java 中不存在。

一种方法是使用 String.format:

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

另一种方法是使用模板库,例如VelocityFreeMarker

于 2012-03-10T03:15:18.347 回答
48

还要考虑java.text.MessageFormat,它使用具有数字参数索引的相关语法。例如,

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

结果string包含以下内容:

A string of ponies.

更常见的是,该类用于其数字和时间格式。此处JFreeChart描述了标签格式的示例;该类格式化游戏的状态窗格。RCInfo

于 2012-03-10T04:41:13.713 回答
10

从 Java 15 开始,您可以使用名为的非静态字符串方法String::formatted(Object... args)

例子:

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

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

输出:

“先 foo,然后是 bar”

于 2020-10-15T16:09:56.747 回答
4

StringSubstitutor可以使用Apache Commons 。

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

此类支持为变量提供默认值。

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

要使用递归变量替换,请调用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"
于 2021-04-19T01:25:42.250 回答
1

您可以使用字符串格式在字符串中包含变量

我使用此代码在字符串中包含 2 个变量:

String myString = String.format("这是我的字符串 %s %2d", variable1Name, variable2Name);

于 2020-07-18T10:33:33.240 回答