我正在尝试编写一个程序,允许用户输入一个短语(例如:“我喜欢猫”
)并将每个单词打印在单独的行上。我已经编写了允许在每个空格处换行的部分,但我不想在单词之间有空行,因为多余的空格强>。我无法使用任何正则表达式
,例如 String.split()
、replaceAll()
或 trim()
>。
我尝试使用几种不同的方法,但如果您不知道可能存在的确切数量,我不知道如何删除空格。我尝试了很多不同的方法
,但似乎没有任何效果。
有没有办法可以将它实现到我已经编写的代码中?
for (i=0; i<length-1;) {
j = text.indexOf(" ", i);
if (j==-1) {
j = text.length();
}
System.out.print("\n"+text.substring(i,j));
i = j+1;
}
或者我怎样才能为它编写一个新的表达式?如有任何建议,我们将不胜感激。
最佳答案
I have already written the part to allow a new line at every space but I don't want to have blank lines between the words because of excess spaces.
如果无法使用trim()
或replaceAll()
,可以使用java.util.Scanner
读取每个单词作为 token 。默认情况下,Scanner
使用空格模式作为查找标记的分隔符。同样,您也可以使用 StringTokenizer
在新行上打印每个单词。
String str = "I like cats";
Scanner scanner = new Scanner(str);
while (scanner.hasNext()) {
System.out.println(scanner.next());
}
输出
I
like
cats
关于java - java 如何编写replaceAll函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076030/