Java String new line

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

    Try:

    System.out.println("I\nam\na\nboy");
    
    0 讨论(0)
  • Full program example, with a fun twist:

    Open a new blank document and save it as %yourJavaDirectory%/iAmABoy/iAmABoy.java. "iAmABoy" is the class name.

    Paste the following code in and read through it. Remember, I'm a beginner, so I appreciate all feedback!

    //The class name should be the same as your Java-file and directory name.
    class iAmABoy {
    
        //Create a variable number of String-type arguments, "strs"; this is a useful line of code worth memorizing.
        public static void nlSeparated(String... strs) {
    
            //Each argument is an str that is printed.
            for (String str : strs) {
    
                System.out.println(str);
    
            }
    
        }
    
        public static void main(String[] args) {
    
            //This loop uses 'args' .  'Args' can be accessed at runtime.  The method declaration (above) uses 'str', but the method instances (as seen below) can take variables of any name in the place of 'str'.
            for (String arg : args) {
    
                nlSeparated(arg);
    
            }
    
            //This is a signature.  ^^
            System.out.print("\nThanks, Wolfpack08!");
        } 
    
    }
    

    Now, in terminal/cmd, browse to %yourJavaDirectory%/iAmABoy and type:

    javac iAmABoy.java
    java iAmABoy I am a boy
    

    You can replace the args I am a boy with anything!

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

    If you simply want to print a newline in the console you can use ´\n´ for newlines.

    If you want to break text in swing components you can use html:

    String s = "<html>first line<br />second line</html>";
    
    0 讨论(0)
  • 2020-11-28 23:40

    I use this code String result = args[0].replace("\\n", "\n");

    public class HelloWorld {
    
        public static void main(String[] args) {
            String result = args[0].replace("\\n", "\n");
            System.out.println(result);
        }
    }
    

    with terminal I can use arg I\\nam\\na\\boy to make System.out.println print out

    I
    am
    a
    boy
    

    0 讨论(0)
  • 2020-11-28 23:43
    System.out.println("I\nam\na\nboy");
    
    System.out.println("I am a boy".replaceAll("\\s+","\n"));
    
    System.out.println("I am a boy".replaceAll("\\s+",System.getProperty("line.separator"))); // portable way
    
    0 讨论(0)
  • 2020-11-28 23:44

    You can also use System.lineSeparator():

    String x = "Hello," + System.lineSeparator() + "there";
    
    0 讨论(0)
提交回复
热议问题