How to center string output using printf() and variable width? [java]

前端 未结 2 441
孤独总比滥情好
孤独总比滥情好 2020-12-21 08:53

I\'m creating an output in Java using printf() to create table headers. One of the columns needs variable width.

Basically it should look like this:



        
相关标签:
2条回答
  • 2020-12-21 09:01

    Use StringUtils.center from the Commons Lang library:

    StringUtils.center(column, "Column Heading".length());
    
    0 讨论(0)
  • 2020-12-21 09:10

    Java does not support the "*" format specifier. Instead, insert the width directly into the format string:

    int spacing = numCoords * 7; //size of column
    System.out.printf("Trial    %" + spacing + "s", "Column Heading");
    
    0 讨论(0)
提交回复
热议问题