0
TMP = String.format("%-25s %25s", STRING1, STRING2);

Whenever I print TMP, it doesn't seem to properly print the table the way I'm looking for

For example:

STRING1 = Test1 & Test12 STRING2 = Hello

Print:
Test1           Hello
Test12           Hello

Why is that happening?

1
  • 2
    Avoid using all-capitals for variable names; in Java, that's a convention that indicates a constant. Commented Sep 9, 2013 at 16:33

2 Answers 2

2

"Test12" has 1 more character than "Test1". Try this

String.format("%-25s\t%25s", string1, string2);
Sign up to request clarification or add additional context in comments.

3 Comments

I suspect a tab is very much not what the OP needs. Probably they were looking to put "Test1" and "Test12" in a 25-character space-padded column.
Yes, I am looking to make sure that there is a certain number of spaces allocated. This assures that each string will always start on the nth character.
@AlexanderKhaosGreenstein Then Peters solution is probably the more likely solution here
2

Most likely your String has padded spaces already

for (String s1 : "Test1,Test12,Test123,Test1234,Test12                    ".split(",")) {
    String tmp = String.format("%-25s %25s", s1, "hello");
    System.out.println(tmp);
}

prints

Test1                                         hello
Test12                                        hello
Test123                                       hello
Test1234                                      hello
Test12                                         hello

You can trim() them before trying to format them.

String tmp = String.format("%-25s %25s", s1.trim(), s2.trim());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.