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

发布于 2024-10-28 02:04:17 字数 445 浏览 7 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

稍尽春風 2024-11-04 02:04:17
String s = String.format("x:%d, y:%d, z:%d", x, y, z);

Java Howto - 设置字符串格式

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

Java Howto - Format a string

天涯离梦残月幽梦 2024-11-04 02:04:17

是的,这是可能的。 String 类包含 format() 方法,其工作原理与您期望的一样。
示例:

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

这里有有关格式化的更多详细信息:
格式化程序语法

Yes, it is possible. The String class contains the format() method, which works like you expect.
Example:

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

Here you have more details about formatting:
formatter syntax

回心转意 2024-11-04 02:04:17

从 JDK 15 开始:

var s = "x:%d, y:%d, z:%d".formatted(x, y, z);

Since JDK 15:

var s = "x:%d, y:%d, z:%d".formatted(x, y, z);
听风念你 2024-11-04 02:04:17

您可以使用 Java 的字符串模板功能进行插值。
它在 JEP 430 中进行了描述,并作为预览功能出现在 JDK 21 中。这是一个使用示例:

String info = STR."x:\{x}, y:\{y}, z:\{z}";

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:

String info = STR."x:\{x}, y:\{y}, z:\{z}";
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文