Java String Pad Left lpad(String base, int len, String pad)

Here you can find the source of lpad(String base, int len, String pad)

Description

Returns the string str left-padded with the string pad to a length of len characters.

License

Apache License

Declaration

public static String lpad(String base, int len, String pad) 

Method Source Code

//package com.java2s;
/*/*from w  ww .jav a  2 s . c om*/
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

public class Main {
    /**
     * Returns the string str left-padded with the string pad to a length of len characters.
     * If str is longer than len, the return value is shortened to len characters.
     */
    public static String lpad(String base, int len, String pad) {
        if (len < 0) {
            return null;
        } else if (len == 0) {
            return "";
        }

        char[] data = new char[len];
        char[] baseChars = base.toCharArray();
        char[] padChars = pad.toCharArray();

        // the length of the padding needed
        int pos = Math.max(len - base.length(), 0);

        // copy the padding
        for (int i = 0; i < pos; i += pad.length()) {
            for (int j = 0; j < pad.length() && j < pos - i; j++) {
                data[i + j] = padChars[j];
            }
        }

        // copy the base
        int i = 0;
        while (pos + i < len && i < base.length()) {
            data[pos + i] = baseChars[i];
            i += 1;
        }

        return new String(data);
    }
}

Related

  1. lpad(int i, int length, char c)
  2. lpad(int length, long number)
  3. lpad(int maxDigits, long val)
  4. lpad(int value, int padLen, char padChar)
  5. lpad(Object str, int len, String padding)
  6. lpad(String input, char padding, int length)
  7. lpad(String input, int length)
  8. lpad(String input, String padChar, int finalLength)
  9. lPad(String input, String replace, int length)