如何在 Java 中构建格式化字符串?
我对 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.println 输出格式化字符串。 out.printf() 但我想将格式化的字符串存储在变量中。
I am somewhat new to Java but I dislike the heavy use of string concatenation I'm seeing in my textbook.
For example, I'd like to avoid doing this:
String s = "x:"+x+"," y:"+y+", z:"+z;
Is it possible to build a string using a notation similar to this:
String s = new String("x:%d, y:%d, z:%d", x, y, z);
Input
x = 1
y = 2
z = 3
Output
"x:1, y:2, z:3"
Note: I understand I can output formatted strings using System.out.printf()
but I want to store the formatted string in a variable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java Howto - 设置字符串格式
Java Howto - Format a string
是的,这是可能的。
String
类包含format()
方法,其工作原理与您期望的一样。示例:
这里有有关格式化的更多详细信息:
格式化程序语法
Yes, it is possible. The
String
class contains theformat()
method, which works like you expect.Example:
Here you have more details about formatting:
formatter syntax
从 JDK 15 开始:
Since JDK 15:
您可以使用 Java 的字符串模板功能进行插值。
它在 JEP 430 中进行了描述,并作为预览功能出现在 JDK 21 中。这是一个使用示例:
You can do interpolation using Java's String Templates feature.
It is described in JEP 430, and it appears in JDK 21 as a preview feature. Here is an example use: