这个 %<s 叫什么?

AKJ*_*AKJ 0 java string format

我最近遇到了以下字符串:“%<s”。我注意到这有以下效果:

String sampleString = "%s, %<s %<s";
String output = String.format(sampleString, "A");
System.out.println(output); // A, A A.
Run Code Online (Sandbox Code Playgroud)

我试图用谷歌搜索这个 %<s 叫什么,但没有成功。从上面的代码我知道我只需要输入一次格式字符串,它就会替换所有 %s & %<s 实例。

只是好奇这个名字叫什么!

小智 5

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

来自Java 文档

当格式说明符包含 '<' ('\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
Run Code Online (Sandbox Code Playgroud)