java 将一串文本打印成多行?爪哇
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14952699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing a string of text into multiple lines? Java
提问by user2086204
I am using the scanner utility to read a sentence inputted from the keyboard. I want to know how to be able to transform this string text into multiple lines..
我正在使用扫描仪实用程序来读取从键盘输入的句子。我想知道如何能够将此字符串文本转换为多行..
So for example, If I were to enter
例如,如果我要输入
"How are you doing?" (two spaces between you and doing)
How would I be able to make this print onto multiple lines?
我怎样才能把这个打印到多行上?
How
are
you
doing?
SOLVEDby using System.out.println(str.replace(" ", "\n"))
解决通过使用System.out.println(str.replace(””, “\ n”))
Thanks all.
谢谢大家。
回答by Achintya Jha
First take input using scanner. Then split the inputed line using input.split(" ") and store it into String array. At last print the array using loop or Arrays.tostring() method.
首先使用扫描仪输入。然后使用 input.split(" ") 拆分输入的行并将其存储到 String 数组中。最后使用循环或 Arrays.tostring() 方法打印数组。
public static void main(String[] args) {
String s ="How are you doing?".replaceAll(" +"," ");
String[] str = s.split(" ");
System.out.println(str.length);
for(String temp: str){
System.out.println(temp);
}
}
Try this : It will print only one space if there are more than two spaces in a given String.
试试这个:如果给定的字符串中有两个以上的空格,它将只打印一个空格。
Try using only System.out.println();
尝试仅使用 System.out.println();
System.out.println(string.replaceAll(" +", " ").replace(" ", "\n"));
回答by Rais Alam
Try below code
试试下面的代码
public static void main(String[] args) {
Scanner a = new Scanner(System.in);
String lines = a.nextLine();
boolean emptyLine = true;
for (String line : lines.split(" ")) {
if (!"".equals(line.trim())) {
System.out.println(line);
emptyLine = true;
} else if (emptyLine) {
System.out.println();
emptyLine = false;
}
}
}
回答by Bohemian
I would do this:
我会这样做:
System.out.println(str.replaceAll(" +", "\n"));
Edit:
编辑:
The calculate the number of non blank chars:
计算非空白字符的数量:
int chars = str.replace(" ", "").length();