java - 获取单词的五个连续组合

标签 java

所以我试图获取五个连续的单词。我有这个输入:

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/

相关文章:

java.lang.NoClassDefFoundError : javax/servlet/http/HttpServletRequest 错误

java - 上传包含拉丁字符的文件

java - JFrame 标题不会正确对齐

java - 图像按钮不可见

java - 如何以编程方式获取和设置 "Super Fast Charging"设置?

java - 使用 Xtext 生成的 Artifact

java - 视网膜显示屏上缓慢滞后的 Javafx 性能

Java GUI - JTextArea 扩展但不收缩

java - "nice"是否影响Java线程的优先级

java - 可以编译 Maven 文件夹结构之外的文件吗?