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?
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.
%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.
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.
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.
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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With