如何在Java中的对齐列中打印字符串?

时间:2013-06-18 02:28:59

标签: java string output stringtokenizer

我对打印字符串提出了一个问题。该计划应该做以下工作: 获取一个String作为参数并标识这些单词并将它们打印成三列对齐: 例如:

the quick brown fox jumped over the lazy dog

并输出应为:

the  quick   brown
fox  jumped  over
the  lazy    dog

我的解决方案是

private void printColumn(String s){
StringTokenizer toker = new StringTokenizer(s);
while (toker.hasMoreTokens()){
    String temp = "";
    for (int i = 0; i < 3; i++){
  temp +=toker.nextToken();
}
    System.out.print(temp);
System.out.println();
}
}

但我的输出未对齐

the  quick  brown
fox  jumped  over
the  lazy  dog

有什么建议吗?

1 个答案:

答案 0 :(得分:4)

使用printf(...)或String.format(...)并添加正确的格式。

不要在每个单词后添加制表符“\ t” 这个解决方案是错误,因为如果一个单词比一个标签空间长,那么它就会搞乱(因为它会在单词后面的下一个标签空间中显示)。

感谢Hovercraft Full Of Eels提供完整的解决方案。

相关问题