如何在java中的字符串中打印\n

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33724850/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:57:57  来源:igfitidea点击:

How to print \n in a String in java

java

提问by Saeed ur Rehman

I want to print \n.

我想打印\n。

String text = "";

text = "\n is used for new line";

but the \n is not showing when I run the code. How to do this?

但是当我运行代码时没有显示 \n 。这该怎么做?

回答by rajuGT

Escape the \with \

逃避\\

text = "\n is used for new line";

回答by Kvam

If you want to actually write the two chars \and nto output, you need to escape the backslash: \\n.

如果要实际写入两个字符\n输出,则需要转义反斜杠:\\n

All escape sequences are listed in the documentation: https://docs.oracle.com/javase/tutorial/java/data/characters.html

文档中列出了所有转义序列:https: //docs.oracle.com/javase/tutorial/java/data/characters.html

回答by Andy Guibert

In java, the \char is an escape character, meaning that the following char is some sort of control character (such as \n \t or \r).

在java中,\char是转义字符,意思是后面的char是某种控制字符(比如\n\t或\r)。

To print literals in Java escape it with an additional \char

要在 Java 中打印文字,请使用附加\字符对其进行转义

Such as:

如:

String text = "\n is used for a new line";
System.out.println(text);

Will print:

将打印:

\n is used for a new line

\n 用于换行

回答by Mohammed Aouf Zouag

You can also use System.lineSeparator(), introduced in Java 8:

您还可以使用System.lineSeparator()Java 8 中引入的:

String result = "cat" + System.lineSeparator() + "dog";
System.out.print(result);

Output:

输出:

cat
dog