Android String Format centerString(String input, int size)

Here you can find the source of centerString(String input, int size)

Description

Center the input string into a new string that is of the indicated size

License

Open Source License

Parameter

Parameter Description
input string to center
size length of the output string

Declaration

public static String centerString(String input, int size) 

Method Source Code

//package com.java2s;

public class Main {
    /***/*from w  w  w  .  j av a  2s .c o  m*/
     * Center the input string into a new string that is of the indicated size
     * @param input string to center
     * @param size length of the output string
     * @return
     */
    public static String centerString(String input, int size) {
        if (input.length() > size) { // if input is already bigger than output
            return input; // just return
        }

        // Build an empty string of the desired size
        char[] spaces = new char[size + 1];
        for (int idx = 0; idx < spaces.length - 1; idx++) {
            spaces[idx] = ' ';
        }
        String strEmpty = new String(spaces);

        // Calculate how much pre and post padding to use
        int diff = size - input.length();
        int trailing = diff / 2;
        int leading = trailing + diff % 2;

        // return with the new string properly centered
        return strEmpty.substring(0, leading) + input
                + strEmpty.substring(0, trailing);
    }
}

Related

  1. format(String formatString, Object... args)
  2. fillSpace(String formatString, int length)
  3. fillString(String formatString, int length, char fillChar, boolean leftFillFlag)
  4. fillZero(String formatString, int length)
  5. format(String message, Object[] params)