在 String.format() 中选择参数
Selecting parameters in String.format()
在 C#
中,您可以指定哪个参数用于带有 para 2: {2}
的格式化字符串。这允许在任意位置和多次使用参数。
有没有办法用标准 java 做到这一点?
是的。您可以定义参数的索引,请参阅 API 的 Argument Index 部分。
例如:
// ┌ argument 3 (1-indexed)
// | ┌ type of String
// | | ┌ argument 2
// | | | ┌ type of decimal integer
// | | | | ┌ argument 1
// | | | | | ┌ type of decimal number (float)
// | | | | | |
System.out.printf("%3$s %2$d %1$f", 1.5f, 42, "foo");
输出
foo 42 1.500000
备注
以下成语都具有相同的格式定义:
String#format
PrintStream#printf
Formatter#format
是的。从https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax我们可以看出占位符的通用公式是
%[argument_index$][flags][width][.precision]conversion
我们对这部分感兴趣
%[argument_index$][flags][width][.precision]conversion
^^^^^^^^^^^^^^^^^
因此,您可以通过将 x$
添加到占位符来实现,其中 x
表示参数编号(从 1 开始索引),例如
String.format("%2$s %1$s", "foo", "bar"); //returns `"bar foo"`
// ^^ ^^ ^^^ ^^^
// | \_____/ |
// | |
// \_________________/
顺便说一句:如果你想使用像 {x}
这样的格式,只需使用 MessageFormat.format
MessageFormat.format("{1} {0}", "foo", "bar") //result: "bar foo"
我认为您正在搜索 String.format()
Returns a formatted string using the specified format string and arguments.
使用:
String.format("%1$s", object);
在 C#
中,您可以指定哪个参数用于带有 para 2: {2}
的格式化字符串。这允许在任意位置和多次使用参数。
有没有办法用标准 java 做到这一点?
是的。您可以定义参数的索引,请参阅 API 的 Argument Index 部分。
例如:
// ┌ argument 3 (1-indexed)
// | ┌ type of String
// | | ┌ argument 2
// | | | ┌ type of decimal integer
// | | | | ┌ argument 1
// | | | | | ┌ type of decimal number (float)
// | | | | | |
System.out.printf("%3$s %2$d %1$f", 1.5f, 42, "foo");
输出
foo 42 1.500000
备注
以下成语都具有相同的格式定义:
String#format
PrintStream#printf
Formatter#format
是的。从https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax我们可以看出占位符的通用公式是
%[argument_index$][flags][width][.precision]conversion
我们对这部分感兴趣
%[argument_index$][flags][width][.precision]conversion
^^^^^^^^^^^^^^^^^
因此,您可以通过将 x$
添加到占位符来实现,其中 x
表示参数编号(从 1 开始索引),例如
String.format("%2$s %1$s", "foo", "bar"); //returns `"bar foo"`
// ^^ ^^ ^^^ ^^^
// | \_____/ |
// | |
// \_________________/
顺便说一句:如果你想使用像 {x}
这样的格式,只需使用 MessageFormat.format
MessageFormat.format("{1} {0}", "foo", "bar") //result: "bar foo"
我认为您正在搜索 String.format()
Returns a formatted string using the specified format string and arguments.
使用:
String.format("%1$s", object);