Tuesday, July 27, 2010

Format a String (JDK1.5)

JDK1.5 simplifies the operation of formatting a String based on parameters.

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");
System.out.println(s);
// output : Welcome Real's HowTo at http://www.rgagnon.com


A printf method has been added to System.out !



System.out.printf
("Welcome %s at %s", "Real's HowTo", "http://www.rgagnon.com");


As you can see, it is now possible to call a method with a variable number of parameters. But it is also possible to use an array (with the new String.format()).



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);
System.out.println(s);
// output : Welcome Real's HowTo at http://www.rgagnon.com (2010 06 26)


You can use this new feature to quickly format strings into table :



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));
}
}


Output:



|FirstName |Init.     |LastName            |
|Real | |Gagnon |
|John |D |Doe |
|John |F. |Kennedy |


To align numbers :



  String format = "%10.2f\n"; // width == 10 and 2 digits after the dot
float [] floats = {123.45f, 99.0f, 23.2f, 45.0f};
for(int i=0; i<floats.length; i++) {
float value = floats[i];
System.out.format(format, value);
}


Output :



    123.45
99.00
23.20
45.00

No comments:

Post a Comment