Pad specific string to string left side - Android java.lang

Android examples for java.lang:String Pad

Description

Pad specific string to string left side

Demo Code

import java.io.UnsupportedEncodingException;
import java.util.*;

public class Main{

    /**//from www . ja va 2s.com
     * Pad specific string to string left side
     *
     * @param strInput   string to be left padded
     * @param intLength  left pad the input string to intLength( in bytes )
     * @param padingChar padding char
     * @return the string after left padding
     */
    public static String leftPad(String strInput, int intLength,
            char padingChar) {
        if (intLength > strInput.length()) {
            byte[] byteResult = new byte[intLength];
            try {
                byte[] byteInput = strInput.getBytes("utf-8");
                System.arraycopy(byteInput, 0, byteResult, intLength
                        - byteInput.length, byteInput.length);
                for (int i = 0; i < (intLength - byteInput.length); i++) {
                    byteResult[i] = (byte) padingChar;
                }
                return new String(byteResult, "utf-8");
            } catch (UnsupportedEncodingException e) {
                Log.e(StringUtilities.class.getName(),
                        ObjectUtilities.printExceptionStack(e));
            }
            return null;
        } else {
            return strInput;
        }
    }

}

Related Tutorials