1

why is it such a difficult task to find a String function to center align my string when left and right align is so simple using Formatter etc.

I want to format my output file

                                Nodes Expanded
                       Euclidean   Manhattan    Chessboard
Input1                     2           2             2
Input2                     6           6             6
Input3                     -           -             -

pseudocode:

    String line1="Nodes Expanded";
    line1.center(50);  //length of string =50

i can use PrintWriter to the String then.

will i have to build a logic for this or am I not aware of some inbuilt function?

change
  • 3,400
  • 7
  • 32
  • 42
  • Related question - [How to center a string using String.format?](http://stackoverflow.com/questions/8154366/how-to-center-a-string-using-string-format) – Cristian Ciupitu Sep 13 '13 at 22:45

1 Answers1

3

Here's one way to center text:

public String center (String s, int length) {
    if (s.length() > length) {
        return s.substring(0, length);
    } else if (s.length() == length) {
        return s;
    } else {
        int leftPadding = (length - s.length()) / 2; 
        StringBuilder leftBuilder = new StringBuilder();
        for (int i = 0; i < leftPadding; i++) {
            leftBuilder.append(" ");
        }

        int rightPadding = length - s.length() - leftPadding;
        StringBuilder rightBuilder = new StringBuilder();
        for (int i = 0; i < rightPadding; i++) 
            rightBuilder.append(" ");

        return leftBuilder.toString() + s 
                + rightBuilder.toString();
    }
}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111