Home > Software engineering >  What is this %<s called?
What is this %<s called?

Time:09-30

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!

CodePudding user response:

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 '<' ('\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

CodePudding user response:

%<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 '<' ('\u003c') 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".

CodePudding user response:

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 '<' ('\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

Code reference:

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

CodePudding user response:

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 '<' ('\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.

  • Related