Question

I want to create something like this, where each line is surrounded by the "pipe" char.

| First Line |
| 100 200    |
| 1000 2000  |
  • In the first line, the right padding is 1 space.
  • In the second line, the right padding is 4 spaces.
  • In the third line is 2 spaces.

I'm trying to do it via printf + formating (and not explicitly calculating a padding number) but I'm having some trouble with the formating syntax. Here's my current code:

System.out.printf("| FIRST LINE" + "%50s\n", "|");
System.out.printf("| 100 200" + "%50s", "|");
System.out.printf("| 1000 2000" + "%50s", "|");

I'm trying to indicate that the maximum per line is 50 chars, being the first character in the line a "pipe" and the last character in the line another "pipe").

The problem is that the 50 spaces are getting placed without taking in consideration the characters already used in the left part (i.e. "| FIRST LINE"). The code above is similar to:

System.out.format("%s %50s\n", "| FIRST LINE", "|");

So, how can I define the output format such that both strings are taken in consideration for the width?

Thanks in advance.

Was it helpful?

Solution

Try Formatter.

e.g.

StringBuffer sb = new StringBuffer();
Formatter f = new Formatter(sb, Locale.getDefault());
f.format("| %-50s |%n", "FIRST LINE");
f.format("| %-50s |%n", "200 100");
f.format("| %-50s |%n", "1000 2000");
String finalResult = sb.toString();
System.out.println(finalResult);

Output:

| FIRST LINE                                         |
| 200 100                                            |
| 1000 2000                                          |

OTHER TIPS

You can use a StringBuilder. It has methods for setting characters and replacing strings. First create a StringBuilder and fill it characters just containing spaces and end of lines. Then put the pipe character in the right place. Finally, replace the spaces in the middle with the formatted string. Don't forget to count the newline characters, or do said method line for line, and add the lines together using another StringBuilder.

Something that will automatically choose the padding to be equal to the longest string plus two characters (like | FIRST LINE | above) is not possible, but would have been pretty neat.

The best I can help you with is the following:

    System.out.println(String.format("| %10s |", "FIRST LINE" ));
    System.out.println(String.format("| %10s |", "100 200" ));
    System.out.println(String.format("| %10s |", "1000 2000" ));

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top