我有点新的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()
输出格式的字符串,但我想存储在一个变量的格式化字符串。
String s = String.format("x:%d, y:%d, z:%d", x, y, z);
对的,这是可能的。该String
类包含format()
方法,像你期望它的工作原理。例:
String s = String.format("x:%d, y:%d, z:%d", x, y, z);
在这里,您有关于格式的更多详细信息:formatter syntax