Java String Pad Left leftPad(String str, int size)

Here you can find the source of leftPad(String str, int size)

Description

Left pad a String with spaces.

License

Open Source License

Parameter

Parameter Description
str String to pad out
size int size to pad to

Return

DOCUMENT ME!

Declaration

public static String leftPad(String str, int size) 

Method Source Code

//package com.java2s;
/*//from w  w  w .  j a  v a  2  s  .co  m
 * 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.
 */

public class Main {
    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();
    }
}

Related

  1. leftPad(String str, int size)
  2. leftPad(String str, int size)
  3. leftPad(String str, int size)
  4. leftPad(String str, int size)
  5. leftPad(String str, int size)
  6. leftPad(String str, int size)
  7. leftPad(String str, int size, char padChar)
  8. leftPad(String str, int size, String delim)
  9. leftPad(String str, int size, String padStr)