Mar 05

Often we need to left or right pad a string, for example when you need a set of strings to be all the same length.

Java introduced Formatter class in 1.5 to provide printf style formatting. We can use this formatting to pad our Strings with spaces. The String class provides a utility format() method that supports this formatting as shown in the following example methods.

public static String rightPad(String s, int width) {
     return String.format("%1$-" + width + "s", s);  
}

public static String leftPad(String s, int width) {
    return String.format("%1$#" + width + "s", s);  
}

written by objects \\ tags: , , , , ,

Apr 15

public static String zeroPad(int value, int width) {
   return String.format("%0"+width+"d", value);
}

written by objects \\ tags: , , ,

Jan 29

The fill() method in the Arrays class is useful for creating string filled with a certain character.

// create a buffer of 9 characters

char[] fill = new char[9];

// Fill the buffer with all '0's

Arrays.fill(fill, '0');

// Create string using the buffer

String zeroes = new String(fill);

// zeroes string now contains "000000000"

written by objects \\ tags: , , , ,