Java String Align Right alignRight(String text, int length)

Here you can find the source of alignRight(String text, int length)

Description

Right align a string by adding spaces on the left up to specified length.

License

Open Source License

Parameter

Parameter Description
text Text to align
length Length of result

Return

Text right aligned

Declaration

public static String alignRight(String text, int length) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**//  w ww.ja  v  a2  s.co m
     * Right align a string by adding spaces on the left up to specified length.
     * @param text Text to align
     * @param length Length of result
     * @return Text right aligned
     */
    public static String alignRight(String text, int length) {
        StringBuffer result = new StringBuffer();

        for (int i = 1; i <= (length - text.length()); i++) {
            result.append(" ");
        }

        result.append(text);

        return result.toString();
    }

    /**
     * Right align a number by adding spaces on the left up to specified length.
     * @param value Number to align
     * @param length Length of result
     * @return Number right aligned
     */
    public static String alignRight(int value, int length) {
        return alignRight(String.valueOf(value), length);
    }
}

Related

  1. alignRight(final Object str, final int size)
  2. alignRight(String data)
  3. alignRight(String str, int length, boolean isEllipsis)
  4. alignRight(String str, int size, char padChar)
  5. alignRight(String substring, int totalWidth, char fill)
  6. alignRight(String val, char pad, int width)