Java - Write code to Left pad a String with spaces.

Requirements

Write code to Left pad a String with spaces.

Demo

/*
 * Copyright (c) 2001-2002, Marco Hunsicker. All rights reserved.
 *
 * This software is distributable under the BSD license. See the terms of the
 * BSD license in the documentation provided with this software.
 *//*from  w ww  .  jav a2  s. co  m*/
 
//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        String str = "book2s.com";
        int size = 42;
        System.out.println(leftPad(str, size));
    }

    private static final String SPACE = " " /* NOI18N */;

    /**
     * Left pad a String with spaces. Pad to a size of n.
     *
     * @param str String to pad out
     * @param size int size to pad to
     *
     * @return DOCUMENT ME!
     */
    public static String leftPad(String str, int size) {
        return leftPad(str, size, SPACE);
    }

    /**
     * Left pad a String with a specified string. Pad to a size of n.
     *
     * @param str String to pad out
     * @param size int size to pad to
     * @param delim String to pad with
     *
     * @return DOCUMENT ME!
     */
    public static String leftPad(String str, int size, String delim) {
        size = (size - str.length()) / delim.length();

        if (size > 0) {
            str = repeat(delim, size) + str;
        }

        return str;
    }

    /**
     * Repeat a string n times to form a new string.
     *
     * @param str String to repeat
     * @param repeat int number of times to repeat
     *
     * @return String with repeated string
     */
    public static String repeat(String str, int repeat) {
        StringBuffer buffer = new StringBuffer(repeat * str.length());

        for (int i = 0; i < repeat; i++) {
            buffer.append(str);
        }

        return buffer.toString();
    }
}