user2950793
user2950793

Reputation: 61

How to set a word in a string to keep changing according to a value?

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

Answers (4)

Mingyu
Mingyu

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?

  • %: The start of Format String
  • 4$: The 4th argument
  • 2: Width of 2
  • s: String

Upvotes: 3

jbindel
jbindel

Reputation: 5635

Use java.util.MesssageFormat

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

tbodt
tbodt

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

Daniel Gabriel
Daniel Gabriel

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

Related Questions