Java String新行

我有像“我是男孩”的string。 我想打印这样的方式“我(\ n新行)是(\ n新行)a(\ n新行)男孩”。

有谁能够帮助我?

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

 System.out.printf("I %n am %na %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是OS不可知的,它是可移植的。 它代表Unix系统上的\n或Windows系统上的\r\n等等。 因此,请勿使用\n ,而应使用%n

这可以通过几种方式来完成。 我提到两个简单的方法。

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

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

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

尝试:

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

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

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

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

评论者 – 如果我错了,请纠正我

\n用于制作单独的行;

例:

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

结果:

 I am boy 

如果你只是想在控制台上打印一个换行符,你可以使用'\ n'换行符。

如果你想在摆动组件中打破文本,你可以使用html:

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

如果你想让你的代码是非特定的,你应该为每个单词使用println

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

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

println总是使用正确的

怎么样%n使用像String.format()格式化?

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

正如这个答案所说,它可以从java 1.5中获得,也是System.getProperty("line.separator")或者System.lineSeparator()另一种方式,就像这两个一样,是独立于操作系统的

完整的程序例子,有趣的转折:

打开一个新的空白文档,并保存为%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的声音!

你可以在你的string中使用<br>标签来显示在html页面中

的System.out.println( “I \越南\娜\ nboy”);

这个作品在input字符之前也会给出一个空格字符

去分裂。

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