【发布时间】:2023-03-28 07:45:02
【问题描述】:
我需要在每三个单词中拆分一个字符串(使用 JAVA)。 例如:
"This is an example of what I need."
输出将是:
This is an
is an example
an example of
example of what
of what I
what I need
I need
感谢您的帮助!
我试过这样。 我不知道如何获取最后两个单词,或者当短语少于 3 个单词时该怎么做。
String phrase = "This is an example of what I need."
String[] splited = phrase.split(" ");
for (int i = 0; i < phraseSplited.length - 2; i++) {
threeWords = splited[i] + " " + splited[i+1] + " " + splited[i+2];
System.out.println(threeWords);
}
【问题讨论】:
-
最后一行 (
I need) 真的应该在结果中吗? -
是的,需要最后一行。
-
那为什么结果中没有单一的“需要”?
-
最简单的更改是,将条件更改为
len - 1,并在循环中添加一个特殊情况if (i == len -1) { print str[i] + " " + str[i+1] } -
split 方法返回字符串数组。
String splited[] = phrase.split(" ");