Java String new line

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

    If you want to have your code os-unspecific you should use println for each word

    System.out.println("I");
    System.out.println("am");
    System.out.println("a");
    System.out.println("boy");
    

    because Windows uses "\r\n" as newline and unixoid systems use just "\n"

    println always uses the correct one

    0 讨论(0)
  • 2020-11-28 23:22

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

    This works It will give one space character also along before enter character

    0 讨论(0)
  • 2020-11-28 23:28

    Go for a split.

    String string = "I am a boy";
    for (String part : string.split(" ")) {
        System.out.println(part);
    }
    
    0 讨论(0)
  • 2020-11-28 23:30

    To make the code portable to any system, I would use:

    public static String newline = System.getProperty("line.separator");
    

    This is important because different OSs use different notations for newline: Windows uses "\r\n", Classic Mac uses "\r", and Mac and Linux both use "\n".

    Commentors - please correct me if I'm wrong on this...

    0 讨论(0)
  • 2020-11-28 23:30

    What about %n using a formatter like String.format()?:

    String s = String.format("I%nam%na%nboy");
    

    As this answer says, its available from java 1.5 and is another way to System.getProperty("line.separator") or System.lineSeparator() and, like this two, is OS independent.

    0 讨论(0)
  • 2020-11-28 23:36

    you can use <br> tag in your string for show in html pages

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