【问题标题】:How to print Strings in aligned columns in Java?如何在 Java 中的对齐列中打印字符串?
【发布时间】:2013-06-18 02:28:58
【问题描述】:

我有一个关于打印字符串的问题。该程序应完成以下工作: 获取一个字符串作为参数并识别单词并将它们打印在对齐的三列中: 示例:

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

有什么建议吗?

【问题讨论】:

  • 您需要知道每列的最大宽度并在其之外填充足够的空间。 this(答案的前半部分)之类的东西展示了基本思想

标签: java string output stringtokenizer


【解决方案1】:

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

不要在每个单词后添加制表符“\t”。
这个解决方案不好,因为如果一个词长于一个制表符空间,它会搞砸(因为它会跳到该词之后的下一个制表符空间)。

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

【讨论】:

    猜你喜欢
    • 2015-02-03
    • 2016-05-11
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 2017-02-03
    相关资源
    最近更新 更多