Java - Write code to Pads a string with characters so that it is "length" characters long.

Requirements

Write code to Pads a string with characters so that it is "length" characters long.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String string = "book2s.com";
        char aChar = 'a';
        int length = 42;
        System.out.println(pad(string, aChar, length));
    }/*from w w  w.  j  ava2  s .  c o m*/

    public static String pad(String string, char aChar, int length) {
        StringBuffer sb = new StringBuffer();

        if (string.length() == length) {
            return string;
        }

        for (int i = 0; (i < (Math.abs(length) - string.length())); ++i) {
            sb.append(aChar);
        }

        if (length >= 0) {
            sb.append(string);
        } else {
            sb.insert(0, string);
        }

        return sb.toString();
    }
}