Android String Pad toPaddedString(String source, int length, char pad, boolean trailing)

Here you can find the source of toPaddedString(String source, int length, char pad, boolean trailing)

Description

to Padded String

License

Open Source License

Declaration

public static String toPaddedString(String source, int length,
            char pad, boolean trailing) 

Method Source Code

//package com.java2s;

public class Main {
    public static String toPaddedString(String source, int length,
            char pad, boolean trailing) {

        int len = source.length();

        if (len >= length) {
            return source;
        }/*from ww  w .  java  2s.  c o m*/

        StringBuffer sb = new StringBuffer(length);

        if (trailing) {
            sb.append(source);
        }

        for (int i = len; i < length; i++) {
            sb.append(pad);
        }

        if (!trailing) {
            sb.append(source);
        }

        return sb.toString();
    }

    public static String toPaddedString(String source, int length,
            String pad, boolean trailing) {

        int len = source.length();

        if (len == length) {
            return source;
        }

        if (len > length) {
            if (trailing) {
                return source.substring(0, length);
            } else {
                return source.substring(len - length, len);
            }
        }

        StringBuffer sb = new StringBuffer(length);
        int padLength = source.length();
        int partLength = (length - padLength) % pad.length();

        if (trailing) {
            sb.append(source);
            sb.append(pad.substring(pad.length() - partLength, pad.length()));
        }

        for (; padLength + pad.length() <= length; padLength += pad
                .length()) {
            sb.append(pad);
        }

        if (!trailing) {
            sb.append(pad.substring(0, partLength));
            sb.append(source);
        }

        return sb.toString();
    }
}

Related

  1. toPaddedString(String source, int length, String pad, boolean trailing)
  2. padLeft(String str, char padding, int upTo)
  3. padString(String source)