简体   繁体   中英

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

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?

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";

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM