簡體   English   中英

從字符串中刪除某些單詞

[英]Removing certain words from a string

我在弄清楚如何從字符串中刪除某些單詞時遇到了一些麻煩。 基本上我有一個字符串。 我將字符串中的每個單詞與數組中的預設單詞數量進行比較。 如果字符串中的單詞與預設單詞之一匹配,我將從字符串中刪除該單詞。

舉例來說,我有一個字符串“ is test test”,運行該方法后,我應該有一個包含單詞“ {” test”,“ sentence”}的數組。這就是我到目前為止所擁有的...

編輯基本上問題是什么都沒有改變,我最終得到{“ is”,“ a”,“ test”,“ sentence”}

    private void fillerWords(){

    String[] commonWords = {"the","of","to","and","a","in","is","it","you","that","he","was","for","on","are","with","as","i"};
    List <String>wordList = new ArrayList<String>(Arrays.asList(commonWords)); 

    //Split words in sentence up by word, put them into array
    String s = "is a test sentance";
    String[] tArray = s.split(" ");
    List <String>list = new ArrayList<String>(Arrays.asList(tArray ));    

    //take out words
    for(int i=0; i<list.size(); i++){
        //Check to see if a sentence word is a common word, if so remove word
        for(int c=0; c<wordList.size(); c++){
            if(wordList.get(c) == list.get(i)){
                list.remove(i);
            }//end if
        }//end for
    }//end for


    for(int x=0; x<list.size(); x++){
        System.out.printf("%s  %s \n", x, list.get(x));
    }

}

}

問題是您要從列表中刪除索引i,然后再遞增i,因此每次刪除時都跳過一個索引。 也許創建另一個稱為輸出的列表,而不是在您遇到不好的單詞時從“列表”中刪除,而是在您遇到好的單詞時將其添加到“輸出”中。

另外,正如故障保護所說,您不能使用“ ==”來比較字符串,而需要使用string1.equals(string2)進行比較。

另外,這是一種無需過多更改即可解決的簡短方法:

這樣更改您的比較塊:

if(wordList.get(c).equals(list.get(i))){
   list.remove(i);
   i--;
   break;
}

使用removeAll()刪除另一個集合中存在的元素。

list.removeAll(wordlist)

這將刪除所有元素list中存在的wordlist

(您的代碼也應該起作用。但這是一種較短的方法)

您不能將字符串與

if(wordList.get(c) == list.get(i)){
            list.remove(i);
        }//end if

您需要做:

if(wordList.get(c).equals(list.get(i))){
            list.remove(i);
        }//end if
    String regex;
    regex = "\\s*\\bword\\b\\s*";//word must to be removed.
    while(out.contains("word"))
    out = out.replaceAll(regex, "");//out if input String and finnaly is out..

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM