%n 和 \n 在 Java 中打印新行的区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31981136/
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 %n and \n for printing a new line in Java
提问by Ashish Krishnan
The documentation of Java specifies to use %n rather than \n for a newline.
Java 的文档指定使用 %n 而不是 \n 作为换行符。
As per the Oracle JavaSE Number documentation
A new line character appropriate to the platform running the application. You should always use %n, rather than \n.
适合运行应用程序的平台的换行符。您应该始终使用 %n,而不是 \n。
What is the prominent difference between both if any?.
如果有的话,两者之间的显着区别是什么?
回答by Abimaran Kugathasan
%n
is portable between various platforms, the value emitted from %n
will suit the underlying platform, whereas value emitted by \n
is same for all the platforms.
%n
在各种平台之间是可移植的,从发出的值%n
将适合底层平台,而发出的值\n
对于所有平台都是相同的。
\n
is the correct newline character for Unix-based systems, other systems may use different characters to represent the end of a line. Windows system use \r\n
, and early MacOS systems used \r
.
\n
是基于 Unix 的系统的正确换行符,其他系统可能使用不同的字符来表示行的结尾。Windows系统使用\r\n
,早期的MacOS系统使用\r
。
回答by Developer Marius ?il?nas
%n is special code (placeholder) for new-line symbol (that might be \r\n or \n) in formatted string and \n is an actual symbol.
%n 是格式化字符串中换行符(可能是 \r\n 或 \n)的特殊代码(占位符),而 \n 是实际符号。
You can think of %n as a symbol that will be replaced with the \r\n or \n in the resulting string.
您可以将 %n 视为将在结果字符串中替换为 \r\n 或 \n 的符号。