String s = "hello %s!";
s = String.format(s, "world");
assertEquals(s, "hello world!"); // should be true
See String.format method.
Alternatively use MessageFormat (java.text.MessageFormat
).
The first example uses the static method MessageFormat.format, which internally creates a MessageFormat for one-time use:
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);
The output is:
At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.
The following example creates a MessageFormat instance that can be used repeatedly:
int fileCount = 1273;
String diskName = "MyDisk";
Object[] testArgs = {new Long(fileCount), diskName};
MessageFormat form = new MessageFormat(
"The disk \"{1}\" contains {0} file(s).");
System.out.println(form.format(testArgs));
The output with different values for fileCount:
The disk "MyDisk" contains 0 file(s).
The disk "MyDisk" contains 1 file(s).
The disk "MyDisk" contains 1,273 file(s).