Java String Pad Left leftPad(String toPad, int numPads)

Here you can find the source of leftPad(String toPad, int numPads)

Description

left Pad

License

Open Source License

Declaration

public static String leftPad(String toPad, int numPads) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    public static String leftPad(String toPad, int numPads) {
        return leftPad(toPad, numPads, " ");
    }/*  w w w  .  j  a va 2s  .  com*/

    public static String leftPad(String toPad, int padLength, String padString) {

        if (toPad == null || toPad.length() == 0)
            return toPad;
        if (padLength < 1)
            return "";

        int stringToPadLength = toPad.length();

        // if pad length < toPad's length, truncate toPad string
        if (stringToPadLength > padLength) {
            return toPad.substring(0, padLength);
        }
        // if pad length = toPad's length, return toPad
        else if (stringToPadLength == padLength) {
            return toPad;
        }

        // build padding until amount to pad is met (or exceeded)
        int numCharsToPad = padLength - stringToPadLength;
        String padding = "";
        while (padding.length() < numCharsToPad) {
            padding += padString;
        }
        // if padding exceeds pad length, trim it
        if (padding.length() > numCharsToPad) {
            padding = padding.substring(0, numCharsToPad);
        }
        return padding + toPad;

    }
}

Related

  1. leftPad(String string, int length)
  2. leftPad(String strInput, int intLength)
  3. leftPad(String targetStr, char appendChar, int length)
  4. leftPad(String text, int length, char padChar)
  5. leftPad(String text, int size)
  6. leftPad(String value, int makeLength, char paddingCharacter)
  7. leftPad(String value, int size, String pad)
  8. leftPad(StringBuilder pStringBuilder, int pLength, char pChar)
  9. leftPadByteArray(byte[] source, int size)