Java String Pad Left lpadSapce(final String src, final int length)

Here you can find the source of lpadSapce(final String src, final int length)

Description

lpad Sapce

License

Open Source License

Declaration

public static String lpadSapce(final String src, final int length) 

Method Source Code

//package com.java2s;
/*/*ww w .ja  va 2s.co m*/
 License:
    
 blueprint-sdk is licensed under the terms of Eclipse Public License(EPL) v1.0
 (http://www.eclipse.org/legal/epl-v10.html)
    
    
 Distribution:
    
 Repository - https://github.com/lempel/blueprint-sdk.git
 Blog - http://lempel.egloos.com
 */

public class Main {
    public static String lpadSapce(final String src, final int length) {
        byte[] sourceArray = nvl(src).getBytes();
        byte[] targetArray = new byte[length];
        int count;

        if (sourceArray.length > length) {
            count = length;
        } else {
            count = sourceArray.length;
        }

        System.arraycopy(sourceArray, 0, targetArray, length - count, count);

        for (int i = 0; i < length - count; i++) {
            targetArray[i] = ' ';
        }

        return new String(targetArray);

    }

    @SuppressWarnings("WeakerAccess")
    public static String nvl(Object value) {
        String result;
        if (value == null) {
            result = "";
        } else {
            result = value.toString().trim();
        }
        return result;
    }

    public static String nvl(Object value, String defaultValue) {
        String result = defaultValue;
        if (value != null) {
            result = value.toString();
        }
        return result;
    }
}

Related

  1. lpad(String str, String chr, int length)
  2. lPad(String string, char[] padding, int length)
  3. lPad(String target, String fix, int length)
  4. lPad(String val, int length, String padChar)
  5. lpadding(String s, int n, String padding)
  6. lpadWithCount(String input, String str, int count)