如何在 Java 中打印添加换行符的字符串?

发布于 2024-12-11 03:13:33 字数 131 浏览 1 评论 0原文

我有一个字符串,

"I am a boy".

我想以这种方式打印它,

"I 
am 
a
boy".

有人可以帮助我吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

往昔成烟 2024-12-18 03:13:33
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.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
无远思近则忧 2024-12-18 03:13:33

您还可以使用 System. lineSeparator()

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

You can also use System.lineSeparator():

String x = "Hello," + System.lineSeparator() + "there";
半葬歌 2024-12-18 03:13:33

示例

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

输出

I 
 am 
 a 
 boy

说明

最好使用 %n 作为操作系统独立的换行符,而不是 \n,并且比使用 System.lineSeparator()

为什么要使用 %n,因为在每个操作系统上,新行引用不同的字符集;

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

LF换行的缩写,CR回车的缩写。转义字符写在括号内。因此,在每个操作系统上,新行代表系统特定的内容。 %n 与操作系统无关,它是可移植的。它代表 Unix 系统上的 \n 或 Windows 系统上的 \r\n 等等。因此,不要使用 \n,而是使用 %n

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.

救星 2024-12-18 03:13:33

可以通过多种方式完成。我提到了两种简单的方法。

  1. 非常简单的方法如下:

    System.out.println("I\nam\na\nboy");
    
  2. 也可以通过连接来完成,如下所示:

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

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");
    
信愁 2024-12-18 03:13:33

尝试:

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

Try:

System.out.println("I\nam\na\nboy");
暮年 2024-12-18 03:13:33

为了使代码可移植到任何系统,我将使用:

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

这很重要,因为不同的操作系统使用不同的换行符号:Windows 使用“\r\n”,经典 Mac 使用“\r”,Mac 和 Linux 都使用“\ n”。

评论者 - 如果我的观点有误,请纠正我......

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...

幼儿园老大 2024-12-18 03:13:33

\n 用于分隔行;

示例:

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

结果:

I
am
a
boy

\n is used for making separate line;

Example:

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

Result:

I
am
a
boy
许仙没带伞 2024-12-18 03:13:33

与平台无关的换行符:

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

输出:

physical
distancing

注释:

  • Java 6:System.getProperty("line.separator")
  • Java 7 和 Java 6 :System.getProperty("line.separator")上面:System.lineSeparator()

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()
生生不灭 2024-12-18 03:13:33

如果您只想在控制台中打印换行符,可以使用 \n 来换行符。

如果您想在 Swing 组件中中断文本,可以使用 HTML 及其

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

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 and its <br>:

String str = "<html>first line<br>second line</html>";
若相惜即相离 2024-12-18 03:13:33

如果你想让你的代码与操作系统无关,你应该为每个单词使用 println

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

,因为 Windows 使用“\r\n”作为换行符,而 unixoid 系统只使用“\n”

println 总是使用正确的换行符

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

习惯成性 2024-12-18 03:13:33

%n 使用像 String.format() 这样的格式化程序怎么样?:

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

这个答案说,它从 java 1.5 开始提供,是 System.getProperty("line.separator") 或的另一种方式System.lineSeparator() 并且,像这两个一样,它是操作系统独立的

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.

是你 2024-12-18 03:13:33

完整的程序示例,有一个有趣的变化:

打开一个新的空白文档并将其另存为 %yourJavaDirectory%/iAmABoy/iAmABoy.java。 “iAmABoy”是班级名称。

将以下代码粘贴并阅读。请记住,我是初学者,所以我感谢所有反馈!

//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!");
    } 

}

现在,在 Terminal/cmd 中,浏览到 %yourJavaDirectory%/iAmABoy 并输入:

javac iAmABoy.java
java iAmABoy I am a boy

您可以将参数 I am a boy 替换为任何内容!

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!

魄砕の薆 2024-12-18 03:13:33

分手。

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

Go for a split.

String string = "I am a boy";
for (String part : string.split(" ")) {
    System.out.println(part);
}
压抑⊿情绪 2024-12-18 03:13:33

我使用此代码 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);
    }
}

与终端我可以使用 arg I\\nam\\na\ \boy 使 System.out.println 打印出

I
am
a
boy

在此处输入图像描述

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

enter image description here

拥有 2024-12-18 03:13:33

这里是!!
NewLine 称为CRLF(回车换行)。

  • 对于Linux和Mac,我们可以使用“\n”。
  • 对于Windows,我们可以使用“\r\n”。

示例:

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

结果:
输出

它对我有用。

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:
output

It worked for me.

屋檐 2024-12-18 03:13:33

您可以在字符串中使用
标记在 html 页面中显示

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

无法言说的痛 2024-12-18 03:13:33

这里我使用的是 split 函数。我从空格中制动了字符串。然后我使用 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]);
         }        
}

Here I am using the split function. I braked String from spaces. then I used println function and printed the value.

    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]);
         }        
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文