假设
- 输入是多个字符串
- 每个字符串输入包含未知数量的行
- 输出应该是输入中每个字符串一列,保留行尾
- 输出列应该是与输入行长度匹配的可变宽度
方法
public static String printColumns(String[] input) {
String result = "";
// Split input strings into columns and rows
String[][] columns = new String[input.length][];
int maxLines = 0;
for (int i = 0; i < input.length; i++) {
columns[i] = input[i].split("\n");
if (columns[i].length > maxLines)
maxLines = columns[i].length;
}
// Store an array of column widths
int[] widths = new int[input.length];
// calculate column widths
for (int i = 0; i < input.length; i++) {
int maxWidth = 0;
for (int j = 0; j < columns[i].length; j++)
if (columns[i][j].length() > maxWidth)
maxWidth = columns[i][j].length();
widths[i] = maxWidth + 1;
}
// "Print" all lines
for (int line = 0; line < maxLines; line++) {
for (int column = 0; column < columns.length; column++) {
String s = line < columns[column].length ? columns[column][line] : "";
result += String.format("%-"+widths[column]+"s", s);
}
result += "\n";
}
return result;
}
用法
String hello = "Hello world\nWelcome\n";
String goodbye = "Goodbye\nSee you in the next life\n";
String dosomething = "Do something\nBe part of us\n";
String[] input = {hello, goodbye, dosomething};
System.out.println(printColumns(input));