Java String Pad Left leftPad(String s, int l)

Here you can find the source of leftPad(String s, int l)

Description

left pad the string passed to a field the size passed

License

Open Source License

Declaration

public static final String leftPad(String s, int l) 

Method Source Code

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

public class Main {
    /**//from   w ww.j av a  2 s  .  co m
     * left pad the string passed to a field the size passed
     */
    public static final String leftPad(String s, int l) {
        return blanks(l - s.length()) + s;
    }

    /**
     * left pad the string passed to a field the size passed with the char passed
     */
    public static final String leftPad(String s, int l, char c) {
        return blanks(l - s.length(), c) + s;
    }

    /**
     * left pad the string buffer passed to a field the size passed
     */
    public static final void leftPad(StringBuffer sb, int l) {
        sb.insert(0, blanks(l - sb.length()));
    }

    /**
     * left pad the string passed to a field the size passed with the char passed
     */
    public static final void leftPad(StringBuffer sb, int l, char c) {
        sb.insert(0, blanks(l - sb.length(), c));
    }

    /**
     * blanks returns the number of blanks requested.
     * The empty string is returned if the number is <= 0
     */
    public static final String blanks(int l) {
        return blanks(l, ' ');
    }

    /**
     * blanks returns the number of the chars requested.
     * The empty string is returned if the number is <= 0
     */
    public static final String blanks(int l, char c) {
        if (l <= 0)
            return "";
        String s = String.valueOf(c);
        StringBuffer sb = new StringBuffer(l);
        for (int i = 0; i < l; i++)
            sb.append(s);
        return sb.toString();
    }
}

Related

  1. leftPad(String input, char padding, int length)
  2. leftPad(String input, int length, char pad)
  3. leftPad(String inStr, int length, char paddingChar)
  4. leftPad(String original, int length, char padChar)
  5. leftPad(String s, char paddingCharacter, int length)
  6. leftPad(String s, int len, char c)
  7. leftPad(String s, int length)
  8. leftPad(String s, int length)
  9. leftPad(String s, int minLength)