如何格式化打印输出,使每个6行的字符串在Java中保持对齐?

时间:2017-05-17 02:29:56

标签: java string formatting alignment printf

例如,让我说我有6个单词/字符串在其他6个字符串之上:

tiger   elephant  dog      fish  cat      jaguar
lion    human     manatee  cow   sphinx   cougar

我希望它排成一行

1 个答案:

答案 0 :(得分:1)

如果我正确理解你的问题,这里有一个可能符合你需求的简单例子:

String strings[][] = new String[][] {
     {"tiger", "elephant", "dog", "fish", "cat", "jaguar"},
     {"lion", "human", "manatee", "cow", "sphinx", "cougar"}
};

for (String[] line : strings) {
    System.out.printf("%-12s %-12s %-12s %-12s %-12s %-12s\n", 
        line[0], line[1], line[2], line[3], line[4], line[5]);
}

输出:

tiger        elephant     dog          fish         cat          jaguar      
lion         human        manatee      cow          sphinx       cougar