所以我试图获取五个连续的单词。我有这个输入:
Pacific Ocean is the largest of the Earth's oceanic divisions
输出应该是这样的:
Pacific
Pacific Ocean
Pacific Ocean is
Pacific Ocean is the
Pacific Ocean is the largest
Ocean
Ocean is
Ocean is the
Ocean is the largest
Ocean is the largest of
is
is the
is the largest
is the largest of
is the largest of the
the
the largest
the largest of
the largest of the
the largest of the Earth's
largest
largest of
largest of the
largest of the Earth's
largest of the Earth's oceanic
of
of the
of the Earth's
of the Earth's oceanic
of the Earth's oceanic divisions
the
the Earth's
the Earth's oceanic
the Earth's oceanic divisions
Earth's
Earth's oceanic
Earth's oceanic divisions
oceanic
oceanic divisions
divisions
我的尝试:
public void getComb(String line) {
String words[] = line.split(" ");
int count = 0;
for (int i = 0; i < words.length; i++) {
String word = "";
int m = i;
while (count < 5) {
count++;
word += " " + words[m];
System.out.println(word);
m++;
}
}
}
但是输出错误!输出:
Pacific
Pacific Ocean
Pacific Ocean is
Pacific Ocean is the
Pacific Ocean is the largest
如何解决?
最佳答案
使用嵌套的 for 循环而不是 while 循环,并在外循环中提前起始词:
public static void getComb(String line) {
String words[] = line.split(" ");
for (int i = 0; i < words.length; i++) {
String word = "";
for (int w = i; w < ((i + 5 < words.length) ? (i + 5) : words.length); w++) {
word += " " + words[w];
System.out.println(word);
}
}
}
请注意((i + 5 < words.length) ? (i + 5) : words.length)
在内部 for 循环的条件中;它是必需的,这样当剩下的单词少于五个时,您就不会访问数组之外的元素 - 没有它,您将得到 ArrayIndexOutOfBoundsException
关于java - 获取单词的五个连续组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22783028/