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

Reply

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions. If the current one is not understandable, plrease refresh the page to get a different one.
G
8
h
F
a
6
Enter the code without spaces and pay attention to upper/lower case.