Here you can find the source of centerString(String input, int size)
Parameter | Description |
---|---|
input | string to center |
size | length of the output string |
public static String centerString(String input, int size)
//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); } }