Java String new line

前端 未结 17 825
情歌与酒
情歌与酒 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: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.

提交回复
热议问题