Reputation: 61
Can someone tell me whats a java method similar to the python's format method where I could replace a variable ?holder in a string with my own ones?
for instance:
t1 = "test"
t2 = "example"
"This is a {0} test {1}".format(t1, t2)
Thanks
Upvotes: 2
Views: 76
Reputation: 33389
From Javadoc: http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html
// Explicit argument indices may be used to re-order output.
formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
// -> " d c b a"
What does %4$2s
mean?
Upvotes: 3
Reputation: 5635
int planet = 7;
String event = "a disturbance in the Force";
String result = MessageFormat.format(
"At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
planet, new Date(), event);
Upvotes: 1
Reputation: 17007
You could use the MessageFormat
class for that, but a far easier and less verbose way would to just use this code:
"This is a " + t1 + " test " + t2
If you need good formatting capabilities, you can use String.format
:
String.format("This is a %s test %s", t1, t2);
Upvotes: 0
Reputation: 3985
You can format a string like this:
String t1 = "test1";
String t2 = "test2";
String.format("This is a %s test %s", t1, t2);
You can have different symbols following the %
sign, check this documentation:
http://docs.oracle.com/javase/6/docs/api/java/util/Formatter.html
Upvotes: 4