How to center a string using String.format?

74,947

Solution 1

I quickly hacked this up. You can now use StringUtils.center(String s, int size) in String.format.

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.assertThat;

import org.junit.Test;

public class TestCenter {
    @Test
    public void centersString() {
        assertThat(StringUtils.center(null, 0), equalTo(null));
        assertThat(StringUtils.center("foo", 3), is("foo"));
        assertThat(StringUtils.center("foo", -1), is("foo"));
        assertThat(StringUtils.center("moon", 10), is("   moon   "));
        assertThat(StringUtils.center("phone", 14, '*'), is("****phone*****"));
        assertThat(StringUtils.center("India", 6, '-'), is("India-"));
        assertThat(StringUtils.center("Eclipse IDE", 21, '*'), is("*****Eclipse IDE*****"));
    }

    @Test
    public void worksWithFormat() {
        String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
        assertThat(String.format(format, StringUtils.center("FirstName", 10), StringUtils.center("Init.", 10), StringUtils.center("LastName", 20)),
                is("|FirstName |  Init.   |      LastName      |\n"));
    }
}

class StringUtils {

    public static String center(String s, int size) {
        return center(s, size, ' ');
    }

    public static String center(String s, int size, char pad) {
        if (s == null || size <= s.length())
            return s;

        StringBuilder sb = new StringBuilder(size);
        for (int i = 0; i < (size - s.length()) / 2; i++) {
            sb.append(pad);
        }
        sb.append(s);
        while (sb.length() < size) {
            sb.append(pad);
        }
        return sb.toString();
    }
}

Solution 2

public static String center(String text, int len){
    String out = String.format("%"+len+"s%s%"+len+"s", "",text,"");
    float mid = (out.length()/2);
    float start = mid - (len/2);
    float end = start + len; 
    return out.substring((int)start, (int)end);
}

public static void main(String[] args) throws Exception{
    // Test
    String s = "abcdefghijklmnopqrstuvwxyz";
    for (int i = 1; i < 200;i++){
        for (int j = 1; j < s.length();j++){
            //center(s.substring(0, j),i);
            System.out.println(center(s.substring(0, j),i));
        }
    }
}

Solution 3

Converted the code found at https://www.leveluplunch.com/java/examples/center-justify-string/ into a handy, small one-line function:

public static String centerString (int width, String s) {
    return String.format("%-" + width  + "s", String.format("%" + (s.length() + (width - s.length()) / 2) + "s", s));
}

Usage:

public static void main(String[] args){
    String out = centerString(10, "afgb");
    System.out.println(out); //Prints "   afgb   "
}

I think it's a very neat solution that's worth mentioning.

Solution 4

Here's the answer using apache commons lang StringUtils.

Please note that you have to add the jar file to the build path. If you are using maven make sure to add commons lang in the dependencies.

import org.apache.commons.lang.StringUtils;
public class Divers {
  public static void main(String args[]){

    String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
    System.out.format(format, "FirstName", "Init.", "LastName");
    System.out.format(format,StringUtils.center("Real",10),StringUtils.center("",10),StringUtils.center("Gagnon",20);

    System.out.format(String.format(format, (Object[])ex));
  }
}

Solution 5

int spaceSize = n - s.length();
int prefixSize = spaceSize / 2;
int suffixSize = (spaceSize + 1) / 2

"one-liner" since Java 11

return n > s.length()
     ? " ".repeat(prefixSize) + s + " ".repeat(suffixSize)
     : s;

Inlining the above vars into one return we can get:

return n > s.length() ? " ".repeat((n - s.length()) / 2) + s + " ".repeat((n - s.length() + 1) / 2**)** : s;


since Java 8

Java 8 has no " ".repeat(10) method. So

  • just replace the " ".repeat(10) with Java 8 analog. See https://stackoverflow.com/a/57514604/601844, and

  • use the same (as Java 11 ☝️) alg:

      int spaceSize = n - s.length();
      int prefixSize = spaceSize / 2;
      int suffixSize = (spaceSize + 1) / 2
      return n > s.length()
           ? space(prefixSize) + s + space(suffixSize)
           : s;
    
    
    private String space(int spaceSize) {
      return generate(() -> " ").limit(spaceSize).collect(joining());
    }
    
Share:
74,947
rana
Author by

rana

Insert test here

Updated on July 26, 2022

Comments

  • rana
    rana almost 2 years
    public class Divers {
      public static void main(String args[]){
    
         String format = "|%1$-10s|%2$-10s|%3$-20s|\n";
         System.out.format(format, "FirstName", "Init.", "LastName");
         System.out.format(format, "Real", "", "Gagnon");
         System.out.format(format, "John", "D", "Doe");
    
         String ex[] = { "John", "F.", "Kennedy" };
    
         System.out.format(String.format(format, (Object[])ex));
      }
    }
    

    output:

    |FirstName |Init.     |LastName            |
    |Real      |          |Gagnon              |
    |John      |D         |Doe                 |
    |John      |F.        |Kennedy             |
    

    I want the output to be centered. If I do not use '-' flag the output will be aligned to the right.

    I did not find a flag to center text in the API.

    This article has some information about format, but nothing on centre justify.