简体   繁体   English

Java 字符串换行

[英]Java String new line

I have a string like我有一个像

"I am a boy".

I would like to print it this way我想这样打印

"I 
am 
a
boy".

Can anybody help me?有谁能够帮我?

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

您还可以使用System.lineSeparator()

String x = "Hello," + System.lineSeparator() + "there";

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()最好使用%n作为独立于操作系统的换行符而不是\\n并且它比使用System.lineSeparator()更容易

Why to use %n , because on each OS, new line refers to a different set of character(s);为什么要使用%n ,因为在每个操作系统上,换行符是指一组不同的字符;

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 . LFLine Feed的首字母缩写, CRCarriage 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. %n与操作系统无关,它是可移植的。 It stands for \\n on Unix systems or \\r\\n on Windows systems and so on.它代表 Unix 系统上的\\n或 Windows 系统上的\\r\\n等等。 Thus, Do not use \\n , instead use %n .因此,不要使用\\n ,而是使用%n

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

尝试:

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

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".这很重要,因为不同的操作系统对换行符使用不同的符号:Windows 使用“\\r\\n”,经典 Mac 使用“\\r”,Mac 和 Linux 都使用“\\n”。

Commentors - please correct me if I'm wrong on this...评论者 - 如果我错了,请纠正我...

\\n is used for making separate line; \\n用于制作单独的行;

Example:例子:

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

Result:结果:

I
am
a
boy

If you simply want to print a newline in the console you can use ´\\n´ for newlines.如果您只想在控制台中打印换行符,您可以使用“\\n”作为换行符。

If you want to break text in swing components you can use html:如果你想在 Swing 组件中打断文本,你可以使用 html:

String s = "<html>first line<br />second line</html>";

Platform-Independent Line Breaks:独立于平台的换行符:

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

Output:输出:

physical
distancing

Notes:笔记:

  • Java 6: System.getProperty("line.separator") Java 6: System.getProperty("line.separator")
  • Java 7 & above: System.lineSeparator() Java 7 及更高版本: System.lineSeparator()

If you want to have your code os-unspecific you should use println for each word如果你想让你的代码不特定于操作系统,你应该对每个单词使用 println

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"因为 Windows 使用 "\\r\\n" 作为换行符,而 unixoid 系统只使用 "\\n"

println always uses the correct one println 总是使用正确的

What about %n using a formatter like String.format() ?:使用像String.format()这样的格式化程序的%n怎么样?:

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 .正如这个答案所说,它可以从 java 1.5 获得,并且是System.getProperty("line.separator")System.lineSeparator()另一种方式,并且与这两个一样,是独立于操作系统的

Full program example, with a fun twist:完整的程序示例,有一个有趣的转折:

Open a new blank document and save it as %yourJavaDirectory%/iAmABoy/iAmABoy.java .打开一个新的空白文档并将其保存为%yourJavaDirectory%/iAmABoy/iAmABoy.java "iAmABoy" is the class name. “iAmABoy”是班级名称。

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:现在,在终端/cmd 中,浏览到%yourJavaDirectory%/iAmABoy并键入:

javac iAmABoy.java
java iAmABoy I am a boy

You can replace the args I am a boy with anything!你可以用任何东西替换 args I am a boy

Go for a split.去分裂。

String string = "I am a boy";
for (String part : string.split(" ")) {
    System.out.println(part);
}

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

This works It will give one space character also along before enter character这有效它会在输入字符之前给出一个空格字符

I use this code String result = args[0].replace("\\\\n", "\\n");我使用此代码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使用终端我可以使用 arg I\\\\nam\\\\na\\\\boy来打印System.out.println

I
am
a
boy

在此处输入图片说明

Here it is!!这里是!! NewLine is known as CRLF (Carriage Return and Line Feed). NewLine 被称为CRLF (回车换行)。

  • For Linux and Mac, we can use "\\n".对于 Linux 和 Mac,我们可以使用“\\n”。
  • For Windows, we can use "\\r\\n".对于 Windows,我们可以使用“\\r\\n”。

Sample:样本:

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

Result:结果:
输出

It worked for me.它对我有用。

Best and easy approach is最好和简单的方法是

"I\nam\na\nboy"

您可以在字符串中使用<br>标签以在 html 页面中显示

Here I am using the split function.这里我使用的是 split 功能。 I braked String from spaces.我从空间刹车字符串。 then I used println function and printed the value.然后我使用了 println 函数并打印了该值。

    public class HelloWorld{

     public static void main(String []args){
              String input = "I am a boy";
              String[] opuput = input.split(" ");
          for (int i = 0; i < opuput.length; i++)
                System.out.println(opuput[i]);
         }        
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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