Java - Write code to Return a copy of s padded with leading spaces so that it's length is length.

Requirements

Write code to Return a copy of s padded with leading spaces so that it's length is length.

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String s = "book2s.com";
        int length = 42;
        System.out.println(leftPad(s, length));
    }/*from ww w  . ja v a 2  s .  c  om*/

    /**
     * Returns a copy of <code>s</code> padded with leading spaces so
     * that it's length is <code>length</code>.  Strings already
     * <code>length</code> characters long or longer are not altered.
     */
    public static String leftPad(String s, int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = length - s.length(); i > 0; i--)
            sb.append(" ");
        sb.append(s);
        return sb.toString();
    }
}