这个 %<s 叫什么?

What is this %<s called?

我最近遇到了以下字符串:“%

String sampleString = "%s, %<s %<s";
String output = String.format(sampleString, "A");
System.out.println(output); // A, A A.

我试过 google 这个 %

很好奇这个名字叫什么!

如果您检查 Formatter Class 中的代码,您会发现:

class 文档中的相关描述:

Relative indexing is used when the format specifier contains a '<' ('\u003c') flag which causes the argument for the previous format specifier to be re-used. If there is no previous argument, then a MissingFormatArgumentException is thrown. formatter.format("%s %s %<s %<s", "a", "b", "c", "d") // -> "a b b b" // "c" and "d" are ignored because they are not referenced

代码参考:

// indexing
static final Flags PREVIOUS = new Flags(1<<8);   // '<'

它们被称为格式说明符。这里你使用的是相对索引。

来自Java documentation

当格式说明符包含 '<' ('\u003c') 标志时使用相对索引,这会导致重新使用前一个格式说明符的参数。如果之前没有参数,则抛出 MissingFormatArgumentException。

formatter.format("%s %s %<s %<s", "a", "b", "c", "d")
// -> "a b b b"
// "c" and "d" are ignored because they are not referenced

%<s 仍然是一个“格式说明符”,就像 %s 一样,除了 %<s 在它的“参数索引”位置有 <。请注意,格式说明符通常具有如下语法:

%[argument_index$][flags][width][.precision]conversion

并且允许使用 < 作为 argument_index 部分 (documentation):

Argument Index

[...]

Another way to reference arguments by position is to use the '<' ('\u003c') flag, which causes the argument for the previous format specifier to be re-used.

文档也没有将 < 部分称为特殊名称,只是“'<' 标志”。

< 标志是相对参数索引。

构造为 %<s,它允许您重复使用先前 %s 格式说明符的参数,在本例中。

您可以在此处阅读有关它和其他格式标记的更多信息:java.util.Formatter

来自 Javadoc:

Relative indexing is used when the format specifier contains a '<' ('\u003c') flag which causes the argument for the previous format specifier to be re-used. If there is no previous argument, then a MissingFormatArgumentException is thrown.