Takes a string and adds a roughly even number of spaces to either side to fit within 20 characters, centering the given text (str). - Java java.lang

Java examples for java.lang:String Whitespace

Description

Takes a string and adds a roughly even number of spaces to either side to fit within 20 characters, centering the given text (str).

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        String filler = " ";
        int lineLength = 42;
        System.out.println(centerString(str, filler, lineLength));
    }//from w  w w.j a  v  a 2  s.  c  o m

    /**
     * Takes a string and adds a roughly even number of spaces to either side to fit within 20 characters, centering the
     * given text (str). Used for the detailed items pane as the Inventory frame's title
     *
     * @param str the String to be centered
     * @param filler the characters which will serve as space-filler around the centered String
     * @param lineLength the length of the line in which str will be centered
     * @return the new String that has been centered
     */
    public static String centerString(String str, String filler,
            int lineLength) {
        String newStr = "";
        int leftSpaces = (int) (Math
                .floor((lineLength - str.length()) / 2.0));
        int rightSpaces = (int) (Math
                .ceil((lineLength - str.length()) / 2.0));

        for (int i = 0; i < leftSpaces; i++) {
            newStr += filler;
        } // for

        newStr += str;

        for (int i = 0; i < rightSpaces; i++) {
            newStr += filler;
        } // for

        return newStr;
    }
}

Related Tutorials