Java String Pad Left leftPad(String strInput, int intLength)

Here you can find the source of leftPad(String strInput, int intLength)

Description

Pad " " to string left side

License

Open Source License

Parameter

Parameter Description
strInput string to be left padded
intLength left pad the input string to intLength( in bytes )

Return

the string after left padding

Declaration

public static String leftPad(String strInput, int intLength) 

Method Source Code

//package com.java2s;
/*/*  w  w w  . j a  v  a2 s  .c  om*/
 * File: $RCSfile$
 *
 * Copyright (c) 2005 Wincor Nixdorf International GmbH,
 * Heinz-Nixdorf-Ring 1, 33106 Paderborn, Germany
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information
 * of Wincor Nixdorf ("Confidential Information"). You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered
 * into with Wincor Nixdorf.
 */

public class Main {
    /**
     * Pad " " to string left side
     *
     * @param strInput  string to be left padded
     * @param intLength left pad the input string to intLength( in bytes )
     * @return the string after left padding
     */
    public static String leftPad(String strInput, int intLength) {
        return leftPad(strInput, intLength, ' ');
    }

    /**
     * Pad specific string to string left side
     *
     * @param strInput    string to be left padded
     * @param intLength   left pad the input string to intLength( in bytes )
     * @param paddingWith padding char
     * @return the string after left padding
     */
    public static String leftPad(String strInput, int intLength, char paddingWith) {
        if (intLength > strInput.length()) {
            byte[] byteResult = new byte[intLength];
            byte[] byteInput = strInput.getBytes();
            System.arraycopy(byteInput, 0, byteResult, intLength - byteInput.length, byteInput.length);

            for (int i = 0; i < (intLength - byteInput.length); i++) {
                byteResult[i] = (byte) paddingWith;
            }

            return new String(byteResult);
        } else {
            return strInput;
        }
    }
}

Related

  1. leftPad(String str, int width, char c)
  2. leftPad(String str, int width, char padding)
  3. leftPad(String str, String character, int size)
  4. leftPad(String string, char pad, int size)
  5. leftPad(String string, int length)
  6. leftPad(String targetStr, char appendChar, int length)
  7. leftPad(String text, int length, char padChar)
  8. leftPad(String text, int size)
  9. leftPad(String toPad, int numPads)