Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting parameters in String.format() [duplicate]

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?

like image 324
Dawnkeeper Avatar asked May 07 '15 10:05

Dawnkeeper


People also ask

What does format () do in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

What is %s in string format?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

What is str format () in Python?

Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.

What is string parameter?

It means you can pass an arbitrary number of arguments to the method (even zero). In the method, the arguments will automatically be put in an array of the specified type, that you use to access the individual arguments.


2 Answers

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
like image 91
Mena Avatar answered Oct 22 '22 00:10

Mena


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") //result: "bar foo"
like image 32
Pshemo Avatar answered Oct 21 '22 23:10

Pshemo