从java中的字符串中删除单词

时间:2013-10-08 19:59:58

标签: java android

有人能告诉我代码中有什么问题吗?

我正在尝试将字符串传递给函数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));

                     }
                   }
                }
            }

        }
} 

1 个答案:

答案 0 :(得分:10)

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