The String class now provides a new method called format(). The parameter substitution mechanism is heavily inspired by C's printf.
String s = String.format
("Welcome %s at %s", "Real's HowTo", "http://www.rgagnon.com");
// output : Welcome Real's HowTo at http://www.rgagnon.com
System.out.printf
("Welcome %s at %s", "Real's HowTo", "http://www.rgagnon.com");
String a[] = { "Real's HowTo", "http://www.rgagnon.com" };
String s = String.format("Welcome %s at %s", a);
System.out.println(s);
Object a[] = { "Real's HowTo", "http://www.rgagnon.com" ,
java.util.Calendar.getInstance()};
String s = String.format("Welcome %1$s at %2$s ( %3$tY %3$tm %3$te )", a);
// output : Welcome Real's HowTo at http://www.rgagnon.com (2004 03 7)
public class Divers {
public static void main(String args[]){
String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
System.out.format(format, "FirstName", "Init.", "LastName");
System.out.format(format, "Real", "", "Gagnon");
System.out.format(format, "John", "D", "Doe");
String ex[] = { "John", "F.", "Kennedy" };
System.out.format(String.format(format, (Object[])ex));
}
}|FirstName |Init. |LastName | |Real | |Gagnon | |John |D |Doe | |John |F. |Kennedy |
Written and compiled by Réal Gagnon ©1998-2007
[ home ]