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

守給你的承諾、 提交于 2021-02-04 19:51:28

问题


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

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).

How can I implement it?


回答1:


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

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:

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

or

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



回答2:


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

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

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




回答3:


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

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 is 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 documentation for more info on this function, and Wikipedia for more info on newlines in general.



来源:https://stackoverflow.com/questions/36330986/how-can-i-add-a-newline-character-to-a-string-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!