我有一个关于打印字符串的问题。该程序应完成以下工作: 获取一个字符串作为参数并识别单词并将它们打印在对齐的三列中: 示例:
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
有什么建议吗?
最佳答案
使用 printf(...) 或 String.format(...) 并添加正确的格式。
不要在每个单词后添加制表符“\t”。
这个解决方案不好,因为如果一个词长于一个制表符空间,它会搞砸(因为它会跳转到词后的下一个制表符空间)。
感谢 Hovercraft Full Of Eels 提供的完整解决方案。
关于java - 如何在 Java 中打印对齐列中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17159692/