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

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

Description

Pads a string left with spaces

License

Open Source License

Parameter

Parameter Description
str a parameter

Return

the padded string

Declaration

public static String leftPad(String str, int length) 

Method Source Code

//package com.java2s;
/*//  w  w w  . j  a v  a  2  s  .c  om
 * Author(s): Pascal Heus (pheus@opendatafoundation.org)
 * 
 * This product has been developed with the financial and
 * technical support of the UK Data Archive Data Exchange Tools
 * project (http://www.data-archive.ac.uk/dext/) and the
 * Open Data Foundation (http://www.opendatafoundation.org)
 * 
 * Copyright 2007 University of Essex (http://www.esds.ac.uk)
 * 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301  USA
 * The full text of the license is also available on the Internet at
 * http://www.gnu.org/copyleft/lesser.html
 * 
 */

public class Main {
    /**
     * Pads a string left with spaces
     *
     * @param str
     * @return the padded string
     */
    public static String leftPad(String str, int length) {
        return (leftPad(str, length, ' '));
    }

    /**
     * Pads a string left with specified character
     *
     * @param str
     * @return the padded string
     */
    public static String leftPad(String str, int length, char ch) {
        int padding = length - str.length();
        if (padding > 0) {
            char[] buf = new char[padding];
            for (int i = 0; i < padding; i++)
                buf[i] = ch;
            return (new String(buf) + str);
        } else
            return (str);
    }
}

Related

  1. leftPad(String s, int z)
  2. leftPad(String srcStr, char padChar, int destLen)
  3. leftPad(String srcString, char c, int length)
  4. leftPad(String srcString, char c, int length)
  5. leftPad(String str, int len, char c)
  6. leftPad(String str, int length, char c)
  7. leftPad(String str, int length, char padding)
  8. leftPad(String str, int maxLength, char placeholder)
  9. leftPad(String str, int num, String padStr)