Center justify string

This example will center align a string based on a width using java, guava and apache commons.

Straight up Java

This snippet will use core java's String.format to center justify a string. We must find how many characters we need to pad by taking the total width and subtracting the size of the string. The padStart in combination of with String.format will pad the string on the left with spaces. Running the String.format will even out the padding by subtracting the remaining width which will move the string to the middle.

@Test
public void center_string_with_java () {
    
    int width = 20;
    String s = "level";
    
    int padSize = width - s.length();
    int padStart = s.length() + padSize / 2;

    s = String.format("%" + padStart + "s", s);
    s = String.format("%-" + width  + "s", s);
    
    assertEquals("       level        ", s);
}

Google Guava

Using guava and a similar technique above we will align the string in the middle of a specified size. Strings.padStart will add spaces to the left of the string or right justify the string. Then calling Strings.padEnd we will add spaces to the right which force the string to be aligned in the center.

@Test
public void center_string_with_google_guava () {
    
    int width = 20;
    String s = "level";
    
    int padSize = width - s.length();
    
    s = Strings.padStart(s, s.length() + padSize / 2, ' ');
    s = Strings.padEnd(s, width, ' ');
    
    assertEquals("       level        ", s);
}

Apache Commons

Apache commons StringUtils.center hides the complexity that the other two snippets show. By providing the string and the size this method will center the text with spaces.

@Test
public void center_string_with_apache_commons () {
    
    String centered = StringUtils.center("level", 20);
    
    assertEquals("       level        ", centered);
}