如何在 Java 中向字符串添加换行符?

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

How can I add a newline character to a String in Java?

javahtmlstringline-breaks

提问by AndreaNobili

In a Java application, I am creating a String like below (by concatenation):

在 Java 应用程序中,我正在创建一个如下所示的字符串(通过串联):

String notaCorrente = dataOdierna + " - " + testoNotaCorrente;

My problem is that I want to add also something like an HTML newline character at the end of this String (that will be shown into an HTML page).

我的问题是我还想在这个字符串的末尾添加一个像 HTML 换行符这样的东西(这将显示在一个 HTML 页面中)。

How can I implement it?

我该如何实施?

回答by ajrskelton

The newline character in Java is "\n" which will look like this:

Java 中的换行符是“\n”,如下所示:

String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "\n";

However, this will not display as you expect on your HTML page. You can try adding an html break tag, or add the 
(Line Feed) and 
(Carriage Return) HTML entities:

但是,这不会像您期望的那样显示在您的 HTML 页面上。您可以尝试添加 html break 标记,或添加
(Line Feed) 和
(Carriage Return) HTML 实体:

String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "<br>";

or

或者

String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "&#13;&#10";

回答by Vishal Gajera

Simply, need to add <br/> (break line tag of HTML).

简单地说,需要添加<br/> (break line tag of HTML).

String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "<br/>";

so, while you are going to display this content, <br/> tagwill rendered on HTML page in form of new line.

因此,当您要显示此内容时,<br/> tag将以新行的形式呈现在 HTML 页面上

回答by Magnus W

For a newline that will result in a line break in HTML, use

对于将导致 HTML 中换行的换行符,请使用

String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "<br>";

For a newline that will result in a line break in your text editor, use

对于将导致文本编辑器中换行的换行符,请使用

String notaCorrente = dataOdierna + " - " + testoNotaCorrente + System.lineSeparator();

And for both, use

对于两者,请使用

String notaCorrente = dataOdierna + " - " + testoNotaCorrente + "<br>" + System.lineSeparator();

Why not \n?

为什么不\n呢?

\nis specific to certain operating systems, while others use \r\n. System.lineSeparator()will get you the one that is relevant to the system where you are executing your application. See the documentationfor more info on this function, and Wikipediafor more info on newlines in general.

\n特定于某些操作系统,而其他操作系统则使用\r\n. System.lineSeparator()将为您提供与您正在执行应用程序的系统相关的一个。有关此功能的更多信息,请参阅文档,有关换行符的更多信息,请参阅维基百科