Java printff字符串只输出格式

Mil*_*lan 1 java printf string-formatting output-formatting

如何使用printf格式化输出.

假设我想在格式化程序中打印以下内容.

testing testing testing testing
testingggg  testingggg  testingggg  testingggg
Run Code Online (Sandbox Code Playgroud)

我不问有关使用"\ t",我问的是printf样式格式?如果有人可以给我建议和例子.或者可以与示例链接.我可以做到符合我的需要.

Bea*_*ham 9

我想你正在寻找Formatter类,它为Java执行printf样式的格式化.

例如,应用于您的输入:

    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());
Run Code Online (Sandbox Code Playgroud)

生产:

testing         testing         testing         testing        
testingggg      testingggg      testingggg      testingggg    
Run Code Online (Sandbox Code Playgroud)