How can I print line side by side in Java?
-
04-06-2021 - |
Question
I couldn't find this anywhere; I might finding it with the wrong keywords.
Pictures paint a thousand words, so let me explain.
Supposed we have a set of unknown number of 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"
I would like a function that produce such result:
String hellogoodbyedo = "
Hello world_________________Goodbye________________________Do Something\n
Welcome_____________________See you in the next life_______Be part of us\n"
In which _ means spaces. Is there a smart way of doing such?
Solution
You can use
System.out.printf("%-20s%-s20s%-20s%n", field1, field2, field3);
OTHER TIPS
Try using tab \t
or counting the number of char in each line and using a loop to generate spaces between each word.
edit split each variable with \n then for each var append the first instance and so on.
There are two parts to the solution.
You can use String.split()
to split each string on the newline characters and store the pieces in an array.
Then use printf
or String.format()
with a format string as shown in the other answers to left-justify each string:
String output = String.format("%-25s%-25s%-25s\n", string1, string2, string3);
Assumptions
- Input is a number of strings
- Each string input contains an unknown number of lines
- Output should be one column per string in the input, conserving line endings
- Output columns shuold be variable width matching the length of input lines
Method
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;
}
Usage
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));
checkout out printf()
here