Quick String Padding

I stumbled on a quick little way to create string padding of various lengths:

private static String padding(final int size, final char val){
    final char[] pad = new char[size];
    Arrays.fill(pad, val);
    return new String(pad);
}

Now obviously, I would recommend using the Jakarta Commons - Lang StringUtils.leftPad(String,int,char) method instead of this (code reuse and all that) but sometimes you don’t have or want external libraries especially if all you need is one method like this; Note too that the StringUtils.leftPad(String,int,char) method actually pads the string to the given lenght rather than just providing the desired amount of padding. Internally it looks like they use a loop to build the required padding. Interesting.

No votes yet