Java - 在字符串中包含变量?

Gra*_*ams 101 java variables insert include quotation-marks

好的,所以我们都应该知道你可以通过以下方式将变量包含到字符串中:

String string = "A string " + aVariable;
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这样:

String string = "A string {aVariable}";
Run Code Online (Sandbox Code Playgroud)

换句话说:无需关闭引号并添加加号.这是非常不吸引人的.

Hov*_*els 110

您始终可以使用String.format(....).即

String string = String.format("A String %s %2d", aStringVar, anIntVar);
Run Code Online (Sandbox Code Playgroud)

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

  • 我知道这是一个见解,但是我看不出`format`比简单的String串联表达式更具吸引力。当需要进行填充,数字格式化等操作时,`format`就会发挥作用。 (2认同)

Jac*_*son 61

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

一种方法是使用String.format:

String string = String.format("A string %s", aVariable);
Run Code Online (Sandbox Code Playgroud)

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


tra*_*god 31

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

String aVariable = "of ponies";
String string = MessageFormat.format("A string {0}.", aVariable);
Run Code Online (Sandbox Code Playgroud)

结果string包含以下内容:

A string of ponies.
Run Code Online (Sandbox Code Playgroud)

更常见的是,该类用于其数字和时间格式.这里JFreeChart描述了标签格式化的一个例子; 该类格式化游戏的状态窗格.RCInfo

  • 对于来自 CSharp 的人来说,这种方式更简单,因为它类似于 C# 中的 string.Format。 (2认同)

hev*_*ev1 19

StringSubstitutor可以使用Apache Commons Text。有关如何将其包含在项目中的信息,请参阅库的依赖关系信息。

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."
Run Code Online (Sandbox Code Playgroud)

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

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

要使用递归变量替换,请调用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"
Run Code Online (Sandbox Code Playgroud)

该库可以在Maven 中央存储库中找到。这是 Maven 依赖项:

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."
Run Code Online (Sandbox Code Playgroud)


Dom*_*din 5

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

例子:

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

String str = "First %s, then %s".formatted(foo, bar);     
Run Code Online (Sandbox Code Playgroud)

输出:

“首先是 foo,然后是酒吧”