java System.out.printf 和 String.format 的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3080112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
difference between System.out.printf and String.format
提问by sutoL
may i know what is the difference between the two in java? i am reading a book and it can either use both of it to display strings.
我可以知道java中两者之间有什么区别吗?我正在读一本书,它可以同时使用它来显示字符串。
回答by BalusC
The first onewrites to the stdoutand the second onereturns a Stringobject.
所述第一个写入到标准输出和所述第二个返回一个String对象。
Which to use depends on the sole purpose. If you want to display the string in the stdout (console), then use the first. If you want to get a handle to the formatted string to use further in the code, then use the second.
使用哪个取决于唯一的目的。如果要在标准输出(控制台)中显示字符串,请使用第一个。如果您想获得格式化字符串的句柄以在代码中进一步使用,请使用第二个。
回答by Greg Case
String.formatreturns a new String, while System.out.printfjust displays the newly formatted String to System.out, sometimes known as the console.
String.format返回一个新的字符串,而System.out.printf只是将新格式化的字符串显示到 System.out,有时也称为控制台。
These two snippets of code are functionally equivalent:
这两个代码片段在功能上是等效的:
String formattedString = String.format("%d is my favorite number", 42);
System.out.print(formattedString);
and
和
System.out.printf("%d is my favorite number", 42);
回答by sns
These two methods exhibit the exact same behavior. We can use the format(...) with String, Java.util.Formatter (J2SE 5) and also with PrintWriter.
这两种方法表现出完全相同的行为。我们可以将 format(...) 与 String、Java.util.Formatter (J2SE 5) 以及 PrintWriter 一起使用。
回答by laura
String.formatformats strings, doesn't display them. I think you mean System.out.println(String.format("......", ....))or some similar construct ?
String.format格式化字符串,不显示它们。我想你的意思是System.out.println(String.format("......", ....))或一些类似的构造?
回答by Richard Fearn
String.formatreturns a formatted string. System.out.printfalso prints the formatted string.
String.format返回一个格式化的字符串。System.out.printf还打印格式化的字符串。

