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

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

Description

Pad some text on the left (i.e., right-align it) until it's a specified width.

License

Open Source License

Parameter

Parameter Description
text string to pad
size length of resulting string

Return

the original text, padded on the left

Declaration

public static String leftPad(String text, int size) 

Method Source Code

//package com.java2s;
// it under the terms of the GNU General Public License as published by

public class Main {
    /**//  w w w.j av  a2 s .c o m
       Pad some text on the left (i.e., right-align it) until it's a
       specified width.  If the text is already longer than the
       desired length, it is returned.
        
       @param text string to pad
       @param size length of resulting string
       @return the original text, padded on the left
    */
    public static String leftPad(String text, int size) {
        int numSpaces = size - text.length();
        if (numSpaces <= 0)
            return text;

        StringBuffer buf = new StringBuffer(size);

        for (int i = 0; i < numSpaces; i++)
            buf.append(' ');
        for (int i = numSpaces; i < size; i++)
            buf.append(text.charAt(i - numSpaces));

        return buf.toString();
    }
}

Related

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