JDK 1.5 中 MessageFormat.format 和 String.format 有什么区别?

发布于 2024-08-31 17:12:25 字数 87 浏览 2 评论 0原文

JDK 1.5 中的 MessageFormat.formatString.format 有什么区别?

What is the difference between MessageFormat.format and String.format in JDK 1.5?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

眼泪淡了忧伤 2024-09-07 17:12:25

简而言之,主要区别在于格式字符串:

  1. MessageFormat.format() 格式字符串接受参数位置(例如 {0}{1 })。示例:

    “今年是 {0} 年!”

    开发人员不必担心参数类型,因为它们通常会根据当前的区域设置进行识别和格式化。

  2. String.format() 格式字符串接受参数类型说明符(例如,%d 表示数字,%s 表示字符串)。示例:

    “今年是%d!”

    String.format() 通常可以让您更好地控制参数的显示方式,这要归功于您可以使用类型说明符指定的许多选项。例如,格式字符串“%-6.2f”指定显示左对齐浮点数,最小值为5。宽度为 6 个字符,精度为 2 位小数。

只需查看这两种方法的 javadoc 即可了解更多详细信息。

Put simply, the main difference is in format string:

  1. MessageFormat.format() format string accepts argument positions (eg. {0}, {1}). Example:

    "This is year {0}!"

    The developer doesn't have to worry about argument types, because they are, most often, recognized and formated according to current Locale.

  2. String.format() format string accepts argument type specifiers (eg. %d for numbers, %s for strings). Example:

    "This is year %d!"

    String.format() generally gives you much more control over how the argument is displayed thanks to many options you can specify with the type specifier. For instance, format string "%-6.2f" specifies to display a left-aligned floating point number with min. width 6 chars and precision of 2 decimal places.

Just have a look at javadoc of both methods to find out more details.

薄情伤 2024-09-07 17:12:25

String.format 只是 Formatter,这是一个“printf-style”格式化程序。另一方面, MessageFormat 使用不同的格式约定,如链接文档中所述。

使用第一个“用于布局调整和对齐,数字、字符串和日期/时间数据的通用格式以及特定于区域设置的输出”,第二个“以语言生成串联消息 -中立方式”。

String.format is just a shortcut to Formatter, this is a "printf-style" formatter. On the other side, MessageFormat uses a different formatting convention, as described in the linked documentation.

Use the first "for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output" and the second "to produce concatenated messages in language-neutral way".

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