String.format不完全正常工作?

时间:2013-09-09 16:28:19

标签: java string format

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

每当我打印TMP时,它似乎没有按照我正在寻找的方式正确打印表格

例如:

STRING1 = Test1& TEST12 STRING2 =你好

Print:
Test1           Hello
Test12           Hello

为什么会这样?

2 个答案:

答案 0 :(得分:2)

"Test12""Test1"多一个字符。试试这个

String.format("%-25s\t%25s", string1, string2);

答案 1 :(得分:2)

很可能你的String已经填充了空格

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

打印

Test1                                         hello
Test12                                        hello
Test123                                       hello
Test1234                                      hello
Test12                                         hello

在尝试格式化之前,您可以trim()

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