Java jdk1.5中MessageFormat.format和String.format的区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2809633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:05:15  来源:igfitidea点击:

difference between MessageFormat.format and String.format in jdk1.5?

javastring-formattingmessageformat

提问by kedar kamthe

What is the difference between MessageFormat.formatand String.formatin JDK 1.5?

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

回答by lbalazscs

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

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

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".

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

回答by Adam Dyga

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. %dfor numbers, %sfor 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.

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

    "This is year {0}!"

    开发人员不必担心参数类型,因为它们通常是根据当前的Locale.

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

    "This is year %d!"

    String.format()由于您可以使用类型说明符指定许多选项,因此通常可以让您更好地控制参数的显示方式。例如,格式字符串"%-6.2f"指定显示一个左对齐的带有 min 的浮点数。宽度为 6 个字符,精度为 2 位小数。

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

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