从java中的字符串中删除单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19257172/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
removing words from a string in java
提问by user2860144
Could anyone tell me what is wrong in my code?
谁能告诉我我的代码有什么问题?
I am trying to pass a string to function removeWords()
and this function removes some information from the String
.
我试图将一个字符串传递给函数removeWords()
,这个函数从String
.
For example if I pass:
例如,如果我通过:
"I Have a Headach"
“我头疼”
the function should return:
该函数应该返回:
"Headach"
“头疼”
However, my function is not working:
但是,我的功能不起作用:
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));
}
}
}
}
}
}
回答by Melih Alt?nta?
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,"");
}
output : Headach
输出 : Headach