问题

我有类似的字符串

"I am a boy".

我想这样打印

"I 
am 
a
boy".

有谁能够帮助我?


#1 热门回答(121 赞)

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

#2 热门回答(92 赞)

你也可以使用System.lineSeparator()

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

#3 热门回答(30 赞)

###例子

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是首字母缩写词2656560453换行符CR是首字母缩写词4333569685 Carriage Return.转义字符写在括号内。因此,在每个操作系统上,新行代表系统特有的东西.%n与操作系统无关,它是可移植的。它代表Unix系统的\n或Windows系统的\r\n等等。因此,请勿使用\n,而是使用%n


原文链接