2012-07-27 41 views
0

刪除某些詞。基本上我有一個字符串。我將字符串中的每個單詞與我在數組中具有的預設數量的單詞相比較。如果字符串中的某個單詞與其中一個預設單詞匹配,則將該單詞從字符串中刪除。從我有一點麻煩搞清楚如何從一個字符串中刪除某些文字字符串

作爲一個例子,我有字符串「是一個測試句」,運行方法後,我應該與單詞的數組{「測試」,「句」}這裏是我迄今...

編輯 基本上問題是,沒有什麼變化,我最終{ 「是」, 「一」, 「測試」, 「句」}

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)); 
    } 

} 

}

+0

你說你要的話{「測試」結束了,「句子」},但你究竟是以什麼結束? – Mercurybullet 2012-07-27 20:16:26

+0

這是什麼問題?粗略地說,它看起來應該起作用。但是,您應該爲停用詞使用HashSet,因爲您可以保存內部循環,所以可以提供更好的運行時性能。 – Jochen 2012-07-27 20:20:39

+0

我最終得到的是{「是」,「一」,「測試」,「句」} ....基本上沒有什麼happnes – SNV7 2012-07-27 20:22:49

回答

3

問題是你從列表中刪除索引i,然後增加i,所以你每次刪除時都跳過一個。也許創造另一個列表稱爲輸出,而不是從「名單」中刪除時你打不好的話,只需添加到「輸出」當你打了良好的口碑。

而且,故障安全說,你不能用「==」比較字符串,你需要使用string1.equals(字符串2)比較。

而且,這裏的修復它不改變太多一小段路:

你比較塊變化,例如:

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

你還是比較雙=字符串。 – Failsafe 2012-07-27 20:30:53

+0

,謝謝,不知道我錯過了... – 2012-07-27 20:31:22

+0

謝謝,它工作正常,現在 – SNV7 2012-07-27 20:32:00

2

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

list.removeAll(wordlist) 

它將從list存在於wordlist刪除所有元素。

(代碼應太,但它是一個較短的方式。)

2

你不能

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 
0
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.. 
+0

這種方式爲我工作:) – 2015-10-11 22:03:13

+1

儘管此代碼可以回答這個問題,提供有關_how_額外的內容及/或_why_它解決了問題會改善答案的長期價值。 – 2015-10-11 22:20:45

+0

這不適用於刪除包含以下內容的單詞:「;」或「,」或... – 2015-10-15 20:20:49

相關問題