Center the contents of the string. - Java java.lang

Java examples for java.lang:String Format

Description

Center the contents of the string.

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) {
        String str = "java2s.com";
        int width = 42;
        char padWithChar = 'a';
        System.out.println(justifyCenter(str, width, padWithChar));
    }//from w w w .  ja v a2  s. co  m

    public static String justifyCenter(String str, final int width,
            char padWithChar) {
        str = str != null ? str.trim() : "";

        int addChars = width - str.length();
        if (addChars < 0) {
            // truncate
            return str.subSequence(0, width).toString();
        }
        int prependNumber = addChars / 2;
        int appendNumber = prependNumber;
        if ((prependNumber + appendNumber) != addChars) {
            ++prependNumber;
        }

        final StringBuilder sb = new StringBuilder();

        while (prependNumber > 0) {
            sb.append(padWithChar);
            --prependNumber;
        }

        sb.append(str);

        while (appendNumber > 0) {
            sb.append(padWithChar);
            --appendNumber;
        }

        return sb.toString();
    }
}

Related Tutorials