如何构建在Java中的格式化字符串?

问题描述 投票:13回答:2

我有点新的Java,但我不喜欢大量使用字符串连接的我看到在我的教科书。

例如,我想避免这样做:

String s = "x:"+x+"," y:"+y+", z:"+z;

是否有可能使用一个类似的符号来构建一个字符串:

String s = new String("x:%d, y:%d, z:%d", x, y, z);

输入

x = 1
y = 2
z = 3

产量

"x:1, y:2, z:3"

注:我知道我可以使用System.out.printf()输出格式的字符串,但我想存储在一个变量的格式化字符串。

java string string-interpolation
2个回答
32
投票
String s = String.format("x:%d, y:%d, z:%d", x, y, z);

Java Howto - Format a string


5
投票

对的,这是可能的。该String类包含format()方法,像你期望它的工作原理。例:

String s = String.format("x:%d, y:%d, z:%d", x, y, z);

在这里,您有关于格式的更多详细信息:formatter syntax

© www.soinside.com 2019 - 2024. All rights reserved.