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

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

Description

left Pad

License

Apache License

Declaration

public static String leftPad(String str, int size) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    private static final int PAD_LIMIT = 8192;

    public static String leftPad(String str, int size) {
        return leftPad(str, size, ' ');
    }/*w ww  . ja v a 2  s. c o  m*/

    public static String leftPad(String str, int size, char padChar) {
        if (str == null) {
            return null;
        }
        int pads = size - str.length();
        if (pads <= 0) {
            return str; // returns original String when possible
        }
        if (pads > PAD_LIMIT) {
            return leftPad(str, size, String.valueOf(padChar));
        }
        return repeat(padChar, pads).concat(str);
    }

    public static String leftPad(String str, int size, String padStr) {
        if (str == null) {
            return null;
        }
        if (isEmpty(padStr)) {
            padStr = " ";
        }
        int padLen = padStr.length();
        int strLen = str.length();
        int pads = size - strLen;
        if (pads <= 0) {
            return str; // returns original String when possible
        }
        if (padLen == 1 && pads <= PAD_LIMIT) {
            return leftPad(str, size, padStr.charAt(0));
        }

        if (pads == padLen) {
            return padStr.concat(str);
        } else if (pads < padLen) {
            return padStr.substring(0, pads).concat(str);
        } else {
            char[] padding = new char[pads];
            char[] padChars = padStr.toCharArray();
            for (int i = 0; i < pads; i++) {
                padding[i] = padChars[i % padLen];
            }
            return new String(padding).concat(str);
        }
    }

    public static String repeat(char ch, int repeat) {
        char[] buf = new char[repeat];
        for (int i = repeat - 1; i >= 0; i--) {
            buf[i] = ch;
        }
        return new String(buf);
    }

    public static boolean isEmpty(CharSequence cs) {
        return cs == null || cs.length() == 0;
    }
}

Related

  1. leftPad(String str, int num, String padStr)
  2. leftPad(String str, int pad)
  3. leftPad(String str, int size)
  4. leftPad(String str, int size)
  5. leftPad(String str, int size)
  6. leftPad(String str, int size)
  7. leftPad(String str, int size)
  8. leftPad(String str, int size)
  9. leftPad(String str, int size, char padChar)