Wednesday, 18 May 2011

String Formatting

Crusty old Java hacks, myself included, use the StringBuffer class (or StringBuilder) to stitch together strings, but Java 5 added String formatting classes to the API to and a ‘C’ style printf(...) to the System.out class to make life easier.

These newer classes are seemingly often under-used, but pretty straight forward...

Take a scenario where we need to format a year value into HTML, underlining the last digit. E.g: 2005 becomes: 2005. In this example, the first snippet of code initialises two variables that describe the split year: the centuryAndDecade and yearDigit:

    String year = "2005";
int length = year.length();
    String centuryAndDecade = year.substring
(0, length - 1);
char yearDigit = year.charAt(length - 1);

Using the old fashion StringBuffer, you can create our desired output like this:

    StringBuffer sb = new StringBuffer("  ");
("Result: " + sb.toString());

But, you can use the StringBuilder and Formatter classes to do the same thing:

    StringBuilder sb1 = new StringBuilder();
    Formatter f =
new Formatter(sb1);
("&nbsp;&nbsp;%3s<u>%c</u>", centuryAndDecade, yearDigit);

Or, you can use printf(...) method to simplify your code even further:

    System.out.printf("&nbsp;&nbsp;%3s<u>%c</u>", centuryAndDecade, yearDigit);

No comments: