如何在 Java 中格式化字符串

2024-01-28

原始问题,但如何格式化这样的字符串:

“第 {1} 步,共 {2} 步”

通过使用 Java 替换变量?在 C# 中这很容易。


看一眼字符串格式 http://download.oracle.com/javase/6/docs/api/java/lang/String.html#format%28java.lang.String,%20java.lang.Object...%29。但请注意,它采用与 C 的 printf 系列函数类似的格式说明符 - 例如:

String.format("Hello %s, %d", "world", 42);

将返回“Hello world, 42”。你可能会发现this http://sharkysoft.com/archive/printf/docs/javadocs/lava/clib/stdio/doc-files/specification.htm在学习格式说明符时很有帮助。安迪·托马斯·克莱默很友善地离开了this http://download.oracle.com/javase/6/docs/api/java/util/Formatter.html#syntax下面评论中的链接,似乎指向官方规范。最常用的是:

  • %s - 插入一个字符串
  • %d - 插入有符号整数(十进制)
  • %f - 插入实数,标准表示法

这与 C# 完全不同,C# 使用带有可选格式说明符的位置引用。 这意味着你不能做这样的事情:

String.format("The {0} is repeated again: {0}", "word");

... 实际上不重复传递给 printf/format 的参数。 (请参阅下面 Scrum Meister 的评论)


如果你只是想直接打印结果,你可能会找到System.out.printf(打印流.printf http://download.oracle.com/javase/6/docs/api/java/io/PrintStream.html#printf%28java.lang.String,%20java.lang.Object...%29)根据你的喜好。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Java 中格式化字符串 的相关文章

随机推荐