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相同.如果我想显示表格数字数据,我特别使用它.
Jac*_*son 61
这称为字符串插值; 它在Java中不存在.
一种方法是使用String.format:
String string = String.format("A string %s", aVariable);
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用模板库,如Velocity或FreeMarker.
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
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)
从 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,然后是酒吧”
| 归档时间: |
|
| 查看次数: |
142098 次 |
| 最近记录: |