How can I print a string adding newlines in Java? Ask Question

How can I print a string adding newlines in Java? Ask Question

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?

ベストアンサー1

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

おすすめ記事