如何在Java中并排打印行?

时间:2012-04-29 18:00:43

标签: java algorithm printing system.out

我在任何地方都找不到;我可能会用错误的关键字找到它。

图片描绘了千言万语,让我解释一下。

假设我们有一组未知数量的String:

String hello = "Hello world\n Welcome\n"
String goodbye = "Goodbye\n See you in the next life\n"
String do = "Do something\n Be part of us\n"

我想要一个产生这样结果的函数:

String hellogoodbyedo = "
  Hello world_________________Goodbye________________________Do Something\n
  Welcome_____________________See you in the next life_______Be part of us\n"

其中 _ 表示空格。有这样一种聪明的方法吗?

5 个答案:

答案 0 :(得分:4)

您可以使用

System.out.printf("%-20s%-s20s%-20s%n", field1, field2, field3);

答案 1 :(得分:4)

尝试使用制表符\t或计算每行中的字符数,并使用循环在每个单词之间生成空格。

编辑用\ n拆分每个变量然后为每个var附加第一个实例,依此类推。

答案 2 :(得分:4)

解决方案有两个部分。

您可以使用String.split()拆分换行符上的每个字符串,并将这些字符存储在数组中。

然后使用printfString.format()格式字符串,如其他答案所示,左对齐每个字符串:

String output = String.format("%-25s%-25s%-25s\n", string1, string2, string3);

答案 3 :(得分:3)

假设

  • 输入是多个字符串
  • 每个字符串输入包含未知行数
  • 输入应该是输入中每个字符串一列,节省行结尾
  • 输出列shuold是与输入行长度匹配的可变宽度

方法

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));

答案 4 :(得分:2)

结帐printf() here