vcmkrtchyan
vcmkrtchyan

Reputation: 2626

How to center a string by formatting in Java?

I want my String to be formatted both from the left and right side, so it always keeps standing in the center.

Let's say I want the total length to be 30 symbols (let's mark spaces as stars to see clearly). I want the following result.

sampleString              -> *********sampleString*********
sampleLongLongString      -> *****sampleLongLongString*****

I tried to do the following.

result = padLeft("", 15) + padRight(myString, 15);

or

result = padLeft(padRight(myString, 15), 15);

For functions,

public static String padRight(String s, int n) {
    return String.format("%1$-" + n + "s", s);
}

public static String padLeft(String s, int n) {
    return String.format("%1$" + n + "s", s);
}

but no result.

Upvotes: 0

Views: 4291

Answers (3)

Bohemian
Bohemian

Reputation: 425198

Here's an easy-to-understand method to do it:

public static String center(String string, int length, char pad) {
    StringBuilder sb = new StringBuilder(length);
    sb.setLength((length - string.length()) / 2);
    sb.append(string);
    sb.setLength(length);
    return sb.toString().replace('\0', pad);
}

With this code, when the total padding required is odd, the right-side padding has one extra pad char. To change the behaviour so that the left side gets the extra pad, change line 2 to:

    sb.setLength((length - string.length() + 1) / 2);

Upvotes: 1

Akash Thakare
Akash Thakare

Reputation: 23002

You can create a method to add padding based on the length of the String.

Basically, you have to decide the total/max(left+right) padding for all the Strings. Please take a look at following method.

It also manages the space inside the String. Method will just return actual String if padding can not be added according to maxPadding.

public static String getPaddedString(String str, char paddingChar) {
    if (str == null) {
        throw new NullPointerException("Can not add padding in null String!");
    }

    int maxPadding = 20;//This is what you have to decide
    int length = str.length();
    int padding = (maxPadding - length) / 2;//decide left and right padding
    if (padding <= 0) {
        return str;// return actual String if padding is less than or equal to 0
    }

    String empty = "", hash = "#";//hash is used as a place holder

    // extra character in case of String with even length
    int extra = (length % 2 == 0) ? 1 : 0;

    String leftPadding = "%" + padding + "s";
    String rightPadding = "%" + (padding - extra) + "s";

    String strFormat = leftPadding + "%s" + rightPadding;
    String formattedString = String.format(strFormat, empty, hash, empty);

    //Replace space with * and hash with provided String
    String paddedString = formattedString.replace(' ', paddingChar).replace(hash, str);
    return paddedString;
}

Following program proves that above method works,

public class Test {

    public static void main(String args[]) {
        System.out.println(getPaddedString("Hello", '*'));
        System.out.println(getPaddedString("Hi23", '@'));
        System.out.println(getPaddedString("Test. .Test", '%'));
        System.out.println(getPaddedString(
            "By the way, It's to long to fix !!", '*'));
    }
}

OUTPUT

************Hello************
@@@@@@@@@@@@@Hi23@@@@@@@@@@@@
%%%%%%%%%Test. .Test%%%%%%%%%
By the way, It's to long to fix !!

Upvotes: 2

Seanimus
Seanimus

Reputation: 567

This method will do the trick.

/**
* @param int w     : length of the formatted string (e.g. 30)
* @param String s  : the string to be formatted
* @param char c    : character to pad with
* @param boolean pr: If s is odd, pad one extra left or right
* @return the original string, with pad 'p' on both sides
*/

private String pad(String s, int w, char c, boolean pr){  
   int pad = w-s.length();  
   String p = "";  

   for (int i=0; i<pad/2; i++)
      p = p + c;

   /* If s.length is odd */  
   if (pad%2 == 1)  
      /* Pad one extra either right or left */
      if (pr) s = s + c;  
      else s = c + s;  
   return (p+s+p)
}

Upvotes: 0

Related Questions