Pad the beginning of the given String with spaces until the String is of the given length. - Java java.lang

Java examples for java.lang:String Pad

Description

Pad the beginning of the given String with spaces until the String is of the given length.

Demo Code

/*//from  w  w w  .  j a  v a 2  s  . co m
 * Static String formatting and query routines.
 * Copyright (C) 2001-2005 Stephen Ostermiller
 * http://ostermiller.org/contact.pl?regarding=Java+Utilities
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * See COPYING.TXT for details.
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String s = "java2s.com";
        int length = 42;
        System.out.println(prepad(s, length));
    }

    /**
     * Pad the beginning of the given String with spaces until
     * the String is of the given length.
     * <p>
     * If a String is longer than the desired length,
     * it will not be truncated, however no padding
     * will be added.
     *
     * @param s String to be padded.
     * @param length desired length of result.
     * @return padded String.
     * @throws NullPointerException if s is null.
     *
     * @since ostermillerutils 1.00.00
     */
    public static String prepad(String s, int length) {
        return prepad(s, length, ' ');
    }

    /**
     * Pre-pend the given character to the String until
     * the result is the desired length.
     * <p>
     * If a String is longer than the desired length,
     * it will not be truncated, however no padding
     * will be added.
     *
     * @param s String to be padded.
     * @param length desired length of result.
     * @param c padding character.
     * @return padded String.
     * @throws NullPointerException if s is null.
     *
     * @since ostermillerutils 1.00.00
     */
    public static String prepad(String s, int length, char c) {
        int needed = length - s.length();
        if (needed <= 0) {
            return s;
        }
        char padding[] = new char[needed];
        java.util.Arrays.fill(padding, c);
        StringBuffer sb = new StringBuffer(length);
        sb.append(padding);
        sb.append(s);
        return sb.toString();
    }
}

Related Tutorials