Java:将二维字符串数组打印为右对齐表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/275338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:44:27  来源:igfitidea点击:

Java: Print a 2D String array as a right-justified table

javaformattingprintf

提问by Chris Conway

What is the bestway to print the cells of a String[][]array as a right-justified table? For example, the input

将数组的单元格打印为右对齐表格的最佳方法是什么String[][]?例如,输入

{ { "x", "xxx" }, { "yyy", "y" }, { "zz", "zz" } }

should yield the output

应该产生输出

  x xxx
yyy   y
 zz  zz

This seems like something that one shouldbe able to accomplish using java.util.Formatter, but it doesn't seem to allow non-constant field widths. The best answer will use some standard method for padding the table cells, not the manual insertion of space characters.

这似乎是人们应该能够使用 完成的事情java.util.Formatter,但它似乎不允许非常数的字段宽度。最佳答案将使用一些标准方法来填充表格单元格,而不是手动插入空格字符。

回答by Chris Conway

Here's an answer, using dynamically-generated format strings for each column:

这是一个答案,对每列使用动态生成的格式字符串:

public static void printTable(String[][] table) {
  // Find out what the maximum number of columns is in any row
  int maxColumns = 0;
  for (int i = 0; i < table.length; i++) {
    maxColumns = Math.max(table[i].length, maxColumns);
  }

  // Find the maximum length of a string in each column
  int[] lengths = new int[maxColumns];
  for (int i = 0; i < table.length; i++) {
    for (int j = 0; j < table[i].length; j++) {
      lengths[j] = Math.max(table[i][j].length(), lengths[j]);
    }
  }

  // Generate a format string for each column
  String[] formats = new String[lengths.length];
  for (int i = 0; i < lengths.length; i++) {
   formats[i] = "%1$" + lengths[i] + "s" 
       + (i + 1 == lengths.length ? "\n" : " ");
 }

  // Print 'em out
  for (int i = 0; i < table.length; i++) {
    for (int j = 0; j < table[i].length; j++) {
      System.out.printf(formats[j], table[i][j]);
    }
  }
}

回答by PhiLho

Indeed, if you specify a width for the fields, it should be right-justified.
If you need to have a dynamic padding, minimal for the longest string, you have to walk the array, getting the maximal width, generate the format string with the width computed from this maxima, and use it for format the output.

实际上,如果您为字段指定宽度,则它应该是右对齐的。
如果您需要动态填充,最长字符串的最小值,则必须遍历数组,获取最大宽度,使用从该最大值计算出的宽度生成格式字符串,并将其用于格式化输出。

回答by Aditya Mukherji

find the length of the longest string..
left pad all the strings with spaces until they r that length + 1
System.out.print them using 2 nested for loops

找到最长字符串的长度..
用空格填充所有字符串,直到它们达到该长度 + 1
System.out.print 使用 2 个嵌套的 for 循环