Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct format string for String.format or similar

I'm sure I've seen String.format used like this before:

String.format("Some {1}, {2}, {3}", var1, var2, var3); 

Does this ring any bells for anyone? Maybe I'm thinking of C#, is there a way of achieving the same in java?

I know you can do something like:

String.format("Some %s, %d, %s", aString, aNumber, aString) 

but the syntax I'm after is for the former...

like image 262
auser Avatar asked Aug 26 '12 18:08

auser


People also ask

Which format is used for string?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Parameter: The locale value to be applied on the format() method.

What is %s in Java?

the %s is a 'format character', indicating "insert a string here". The extra parameters after the string in your two function calls are the values to fill into the format character placeholders: In the first example, %s will be replaced with the contents of the command variable.

What is %p format string?

%p expects the argument to be of type (void *) and prints out the address. Whereas %x converts an unsigned int to unsigned hexadecimal and prints out the result.


1 Answers

What you are looking for is MessageFormat, which uses a given format and input parameters, e.g.

MessageFormat.format("Some {0}, {1}, {2}", var1, var2, var3); 

And as already mentioned, String.format can still do the job using the alternate syntax, but it is less powerful in functionality and not what you requested.

like image 131
Tobias N. Sasse Avatar answered Sep 21 '22 15:09

Tobias N. Sasse