2013-10-08 144 views
1

任何人都可以告訴我我的代碼中出現了什麼問題嗎?從java中的字符串中刪除單詞

我想通過一個字符串功能removeWords()和此功能從String刪除一些信息。

例如,如果我通過:

「我有一個頭痛的」

函數應該返回:

「頭痛的」

然而,我的功能不起作用:

public class WordChosen extends Activity { 

    private TextView wordsList; 
    private String symptom; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_word_chosen); 

     //Getting String from VoiceRecognition Activity and displaying it 

     Intent intent = getIntent(); 
     String wordChosen = intent.getExtras().getString("wordChosen"); 

     //casting the string with TextView to display the result 
     wordsList = (TextView) findViewById(R.id.wordChosen); 

     Log.v("Word List:", "+++++"+wordChosen); 
     //Setting text to be displayed in the textView 

     removeWords(wordChosen); 
     Log.v("removewords:", "------- message is displayed"); 



    } 

    public void removeWords(String wordList) 
    { 
     ArrayList<String> stopList = null; 
     stopList.add("i"); 
     stopList.add("have"); 
     stopList.add("a"); 

     ArrayList<String> result = new ArrayList<String>(Arrays.asList(wordList.split(" "))); 
     for(int i=0; i<result.size();i++) 
     { 
      for(int j=0; j<stopList.size();j++) 
      { 

       if (result.get(i).equals(stopList.get(j))) { 
        break; 
       } 
       else { 

        if(j==stopList.size()-1) 
        { 

         wordsList.setText(result.get(i)); 

        } 
        } 
       } 
      } 

     } 
} 
+0

它是什麼返回您的投入? – Prateek

+0

你目前的成績是? – fasteque

+1

字符串是不可變的。您將需要從您的方法返回一個新的字符串。 – GriffeyDog

回答

9
public static void main(String[] args) { 
    String word = "I Have a Headach"; 
    String remove = "I Have a "; 
    System.out.println(removeWords(word, remove)); 
} 

public static String removeWords(String word ,String remove) { 
    return word.replace(remove,""); 
} 

輸出:Headach

+3

雖然我想這在技術上提供了一個替代解決方案的問題,它的範圍有限,可能不太有用的OP。 – AndyPerfect

+1

@AndyPerfect正確。更好的答案(從字符串中刪除多個單詞)可以[在此處找到](http://stackoverflow.com/a/4769336/1276636)。 – Sufian