How do I format output by using printf.

suppose i want to print following in formatter.

testing testing testing testing
testingggg  testingggg  testingggg  testingggg

I am not asking about using "\t", I am asking on printf style formatting? If some one can give me suggestion and example. Or may be link with example. I can do it to fit my need.

有帮助吗?

解决方案

I think you're looking for the Formatter class, which does printf-style formatting for Java.

For example, applied to your input:

    StringBuilder sb = new StringBuilder();
    Formatter formatter = new Formatter(sb, Locale.US);

    formatter.format("%1$-15s %2$-15s %3$-15s %4$-15s\n", "testing", "testing", "testing", "testing");
    formatter.format("%1$-15s %2$-15s %3$-15s %4$-15s", "testingggg", "testingggg", "testingggg", "testingggg");

    System.out.println(sb.toString());

Produces:

testing         testing         testing         testing        
testingggg      testingggg      testingggg      testingggg    

其他提示

You can use System.out.printf("%sggg" , t)

Where t = "testing" and ggg is just appended onto this string.

Hope this helps :D

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top