如何通过LinkedList迭代并在Java中删除其某些单词



尝试从linkedlist中删除一些单词。这是我用于测试的数据:
String[] stopwords = {"the","and"};
nwl = LinkedList<String>(Arrays.asList(input));
String input = "the and of the "
我期望得到的结果是:[of],但我得到了:[the, end, of, the]

for (Iterator<String> iter = nwl.iterator(); iter.hasNext();) {
  String word = iter.next();
    for (int i = 0; i < nwl.size(); i++){
      if(word == stopwords[i]) {
        iter.remove();
      }
    }
}

比较字符串时,需要使用.equals()方法而不是==操作员。因此,您需要将if (word == stopwords[i])更改为if(word.equals(stopwords[i]))

更长的版本:

大概说,==操作员确定两个变量是否指向同一对象(在我们的情况下:wordstopwords[i]是否在同一字符串对象处)。.equals()方法确定两个对象是否相同(内容明智)。如果您的情况,该程序未能产生所需的输出,因为您有两个持有相同内容的不同不同的字符串。因此,通过==比较它们会产生false,而通过.equals()进行比较,则得出`true。

编辑

阅读了链接中发布的程序后,我找到了几件事:首先,必须将LOOP条件的内部状态更改为i < stopwords.length。其次,newWordList对象未正确初始化。这是新的LinkedList<String>(Arrays.asList(parts)),这意味着LinkedList将包含一个单字符串元素,其值为the and of the,这不是您想要的。您希望LinkedList包含四个字符串元素,如下所示:

  • 元素0:the
  • 元素1:and
  • 元素2:of
  • 元素3:the

因此,初始化需要更改为new LinkedList<String>( Arrays.asList(parts.split(" ")))。具体来说,parts.split(" ")将给定的字符串(split)折断为单独的单词,返回这些单词的数组。

public static void main (String[] args) throws java.lang.Exception
{
    String[] stopwords = { "the", "and" };
    String parts = "the and of the";
    LinkedList<String> newWordList = new LinkedList<String>(
      Arrays.asList(parts.split(" ")));
    for (Iterator<String> iter = newWordList.iterator(); iter.hasNext();) {
        String word = iter.next();
        for (int i = 0; i < stopwords.length; i++) {
            if (word.equals(stopwords[i])) {
                iter.remove();
            }
        }
    }
    System.out.println(newWordList.toString());
}

最新更新