Selecting parameters in String.format() [duplicate

2019-01-19 19:50发布

问题:

This question already has an answer here:

  • Java Equivalent to .NET's String.Format 6 answers

In C# you can specify which parameter is used for a formatted string with para 2: {2}. This allows for using parameters in arbitrary places and multiple times.

Is there a way to do this with standard java?

回答1:

Yes. You can define the argument's index, see the Argument Index section of the API.

For instance:

//                 ┌ 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");

Output

foo 42 1.500000

Note

The following idioms all share the same format definitions:

  • String#format
  • PrintStream#printf
  • Formatter#format


回答2:

I think you are searching for String.format()

Returns a formatted string using the specified format string and arguments.

Use:

String.format("%1$s", object);


回答3:

Yes. From https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html#syntax we can see that general formula of placeholders is

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

We are interested in this part

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

So you can do it by using adding x$ to your placeholder where x represents parameter number (indexed from 1) like

String.format("%2$s %1$s", "foo", "bar"); //returns `"bar foo"`
//              ^^   ^^     ^^^    ^^^
//               |    +-----+      |
//               |                 |
//               +-----------------+

BTW: if you want to use formatting like {x} simply use MessageFormat.format

MessageFormat.format("{1} {0}", "foo", "bar")