如何使用 printf 格式化输出。
假设我想在格式化程序中打印以下内容。
testing testing testing testing
testingggg testingggg testingggg testingggg
我不是在问使用“\t”,我是在问 printf 样式格式?如果有人可以给我建议和例子。或者可能与示例链接。我可以做到这一点以满足我的需要。
最佳答案
我认为您正在寻找 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());
产生:
testing testing testing testing
testingggg testingggg testingggg testingggg
关于Java printff 字符串只输出格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8609249/