left Justify a string with padding char - Java java.lang

Java examples for java.lang:String Pad

Description

left Justify a string with padding char

Demo Code

//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String sourceString = "java2s.com";
        int targetLen = 42;
        char pad = 'a';
        System.out.println(leftJustify(sourceString, targetLen, pad));
    }/*from   ww  w  . j  ava 2 s . c o  m*/

    public static String leftJustify(String sourceString, int targetLen,
            char pad) throws IndexOutOfBoundsException {
        int sourceLen = sourceString.length();
        char[] buffer = new char[targetLen];

        if (targetLen < sourceLen) {
            // Just truncate
            sourceString.getChars(0, targetLen, buffer, 0);
        } else {
            int i = 0;

            // Add String
            while (i < sourceLen) {
                buffer[i] = sourceString.charAt(i++);
            }
            // Pad Right
            while (i < targetLen) {
                buffer[i++] = pad;
            }
        }
        return new String(buffer);
    }

    public static int length(String source) {
        int result = 0;
        if (isNotEmpty(source)) {
            result = source.length();
        }
        return result;
    }

    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

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

Related Tutorials