简体   繁体   中英

What is this %<s called?

I have recently come across this following string: "%<s". I noticed that this has the following effect:

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

I tried to google what this %<s is called, but to no avail. I know from the above code that I just need to input the format string once, and it will replace all instances of %s & %<s.

Just curious what this name is called!

They are called format specifiers. Here you are using relative indexing.

From the Java documentation :

Relative indexing is used when the format specifier contains a '<' ('<') 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

%<s is still a "format specifier", just like %s , except that %<s has < in its "argument index" position. Note that a format specifier in general has a syntax like this:

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

and the it is allowed to use < as the argument_index part ( documentation ):

Argument Index

[...]

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

The documentation doesn't call the < part a special name either, just "the '<' flag".

If you check the code from Formatter Class you will find:

Related description from the class documentation:

Relative indexing is used when the format specifier contains a '<' ('<') 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") // -> "abbb" // "c" and "d" are ignored because they are not referenced

Code reference:

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

The < flag is a relative argument index.

Constructed as %<s , it allows you to re-use the argument for the previous %s format specifier, in this case.

You can read more about it and other formatting flags here: java.util.Formatter

From the Javadoc:

Relative indexing is used when the format specifier contains a '<' ('<') 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM