Java String new line

前端 未结 17 777
情歌与酒
情歌与酒 2020-11-28 23:17

I have string like

\"I am a boy\".

I want to print like this way

\"I 
am 
a
boy\".

Can anybody help me?<

相关标签:
17条回答
  • 2020-11-28 23:45

    \n is used for making separate line;

    Example:

    System.out.print("I" +'\n'+ "am" +'\n'+ "boy"); 
    

    Result:

    I
    am
    boy
    
    0 讨论(0)
  • 2020-11-28 23:46

    Platform-Independent Line Breaks

    finalString = "physical" + System.lineSeparator() + "distancing";
    System.out.println(finalString);
    

    Output:

    physical
    distancing
    

    Notes:
    Java 6: System.getProperty("line.separator")
    Java 7 & above: System.lineSeparator()
    
    0 讨论(0)
  • 2020-11-28 23:47

    It can be done several ways. I am mentioning 2 simple ways.

    1. Very simple way as below:

      System.out.println("I\nam\na\nboy");
      
    2. It can also be done with concatenation as below:

      System.out.println("I" + '\n' + "am" + '\n' + "a" + '\n' + "boy");
      
    0 讨论(0)
  • 2020-11-28 23:48

    Example

    System.out.printf("I %n am %n a %n boy");
    

    Output

    I 
     am 
     a 
     boy
    

    Explanation

    It's better to use %n as an OS independent new-line character instead of \n and it's easier than using System.lineSeparator()

    Why to use %n, because on each OS, new line refers to a different set of character(s);

    Unix and modern Mac's   :   LF     (\n)
    Windows                 :   CR LF  (\r\n)
    Older Macintosh Systems :   CR     (\r)
    

    LF is the acronym of Line Feed and CR is the acronym of Carriage Return. The escape characters are written inside the parenthesis. So on each OS, new line stands for something specific to the system. %n is OS agnostic, it is portable. It stands for \n on Unix systems or \r\n on Windows systems and so on. Thus, Do not use \n, instead use %n.

    0 讨论(0)
  • Here it is!! NewLine is known as CRLF(Carriage Return and Line Feed).

    • For Linux and Mac, we can use "\n".
    • For Windows, we can use "\r\n".

    Sample:

    System.out.println("I\r\nam\r\na\r\nboy");
    

    Result:

    It worked for me.

    0 讨论(0)
提交回复
热议问题