mum
mum

Reputation: 1645

How input parameter in String?

I want put value of a at {0}. With C#, I code as:

String a="123"
String b="Xin chao: {0}, ban the nao";
String c=String.Format(b,a);

But in Java I don't know. Can you help me?

Upvotes: 2

Views: 2307

Answers (4)

Vikdor
Vikdor

Reputation: 24124

Java's counterpart is java.text.MessageFormat that allows placeholders like the one in your question can be replaced using format method as

String a = "123";
MessageFormat.format("Xin chao: {0}, ban the nao", a);

Upvotes: 5

Riccardo
Riccardo

Reputation: 1520

String b= "Xin chao: %s";
String bF = String.format(b,"123");

Upvotes: 3

m0skit0
m0skit0

Reputation: 25873

If you don't know where the {0} will appear, you can use String.replaceAll() method:

    String a = "123";
    String b = "Xin chao: {0}, ban the nao";
    String c = b.replaceAll("\\{0\\}", a);

You might want to check StringEscapeUtils to do automatic escaping.

Upvotes: 0

pap
pap

Reputation: 27614

See String.format(String format, Object... args).

For instance

String s = String.format("Xin chao: %1$s", "123");

Upvotes: 2

Related Questions