Java String Left Justify leftJustify(String s, int maxLength)

Here you can find the source of leftJustify(String s, int maxLength)

Description

Left justify a string, and fill to a given length with the blanks.

License

Open Source License

Declaration

public static String leftJustify(String s, int maxLength) 

Method Source Code

//package com.java2s;
/*//w  w  w  .  java  2 s . c om
 * Copyright (c) 2008-2011 Simon Ritchie.
 * All rights reserved. 
 * 
 * This program is free software: you can redistribute it and/or modify 
 * it under the terms of the GNU Lesser General Public License as published 
 * by the Free Software Foundation, either version 3 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 Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License 
 * along with this program.  If not, see http://www.gnu.org/licenses/>.
 */

public class Main {
    /** 
     * Left justify a string, and fill to a given length with the blanks.
     * If the length of the string is greater than "maxLength" characters, return only 
     * the first, left "maxLength" characters. 
     */
    public static String leftJustify(String s, int maxLength) {
        return leftJustify(s, maxLength, ' ');
    }

    /** 
     * Left justify a string, and fill to a given length with the character <code>fill</code>.
     * If the length of the string is greater than "maxLength" characters, return only 
     * the first, left "maxLength" characters. 
     */
    public static String leftJustify(String s, int maxLength, char fill) {
        if (s == null || maxLength == 0) {
            return s;
        }
        // If the string has more than "maxLength" characters, 
        // return only the first "maxLength" characters of the string. 
        if (s.trim().length() > maxLength) {
            return s.substring(0, maxLength).trim();
        }

        StringBuffer sb = new StringBuffer(s.trim());

        // Append as many blanks as needed to reach "maxLength". 
        while (sb.length() < maxLength) {
            sb.append(fill);
        }

        return sb.toString();

    }
}

Related

  1. LeftAdjust(String s, int len, char pad)
  2. leftJustify(long v, int width)
  3. leftJustify(String sourceString, int targetLen, char pad)
  4. leftJustify(String str, int width)
  5. leftJustify(String string, int width)
  6. leftJustify(String value, int width)