首页 > 解决方案 > 删除数组中的重复单词句子

问题描述

给定一个确定单词输出、每个单词长度和单词重复次数的问题,我有以下代码能够确定下面每个单词的单词和长度:

String sentence;
String charSentence;
String[] wordOutput;

private void analyzeWords(String s) {
    String[] words = sentence.split(" ");
    wordOutput = new String[words.length];
    int[] repeats = new int[words.length];

    // Increment a single repeat
    for (int i = 0; i < words.length; i++) {

        repeats[i] = 1;

        // Increment when repeated.
        for (int j = i + 1; j < words.length - 1; j++) {
            if (words[i].equalsIgnoreCase(words[j])) {
                repeats[i]++;
            }
        }

        wordOutput[i] = words[i] + "\t" + words[i].length() + "\t" + repeats[i];
    }

当我运行程序时,我得到以下输出:

Equal   5   2
Equal   5   1 <- This is a duplicate word and should not be here when it repeats.

有谁知道我的问题在哪里?与我的重复数组有关的东西吗?

标签: javaarrays

解决方案


第一个问题是,在内部 for 循环中,您从i+1to循环length-1。您需要循环直到length. 其次,您需要确定在 中是否出现任何单词,String如果出现,请使用continue语句。你可以做:

outer:
for (int i = 0; i < words.length; i++) {

    repeats[i] = 1;
    for(int index = i-1; index >= 0; index--) {
        if(words[i].equals(words[index])) {
            continue outer;
        }
    }
    ...
}

null但是,这样做的问题是列表末尾会有值,因为您指定的Array长度与单词数相同。要解决此问题,您可以执行以下操作:

 wordOutput = Arrays.stream(wordOutput).filter(e-> e!= null).toArray(String[]::new);

这将过滤掉null

输出:

(输入String:)"This is a String is a with a lot lot of this repeats repeats"

This    4   2
is      2   2
a       1   3
String  6   1
with    4   1
lot     3   2
of      2   1
this    4   1
repeats 7   2

推荐阅读