Java String Pad Right rightPad(String str, int size, String padStr)

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

Description

right Pad

License

Apache License

Declaration

public static String rightPad(String str, int size, String padStr) 

Method Source Code

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

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

    public static String rightPad(String str, int size, String padStr) {
        if (str == null) {
            return null;
        }/*from  w  w  w.  ja  v a 2s.c  o  m*/
        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 rightPad(str, size, padStr.charAt(0));
        }

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

    public static String rightPad(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 rightPad(str, size, String.valueOf(padChar));
        }
        return str.concat(repeat(padChar, pads));
    }

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

    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);
    }
}

Related

  1. rightPad(String str, int size)
  2. rightPad(String str, int size, char padChar)
  3. rightPad(String str, int size, char padChar)
  4. rightPad(String str, int size, char padChar)
  5. rightPad(String str, int size, char padChar)
  6. rightPad(String str, int width)
  7. rightPad(String str, int width, char padding)
  8. rightPad(String str, String pad, int len)
  9. rightPad(String string, int length)