在java中从字符串中删除单词
有人能告诉我我的代码出了什么问题吗 我试图将字符串传递给函数在java中从字符串中删除单词,java,android,Java,Android,有人能告诉我我的代码出了什么问题吗 我试图将字符串传递给函数removeWords(),该函数从字符串中删除一些信息 例如,如果我通过: “我头痛” 该函数应返回: “头痛” 但是,我的功能不起作用: public class WordChosen extends Activity { private TextView wordsList; private String symptom; @Override protected void onCreate(Bu
removeWords()
,该函数从字符串中删除一些信息
例如,如果我通过:
“我头痛”
该函数应返回:
“头痛”
但是,我的功能不起作用:
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));
}
}
}
}
}
}
公共类扩展活动{
私有文本视图单词列表;
私家弦征;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u word\u选中);
//从VoiceRecognition活动获取字符串并显示它
Intent=getIntent();
String WordSelected=intent.getExtras().getString(“WordSelected”);
//使用TextView强制转换字符串以显示结果
wordsList=(TextView)findViewById(R.id.WordSelected);
Log.v(“单词列表:”,“+”+单词选择);
//设置要在文本视图中显示的文本
移除单词(已选择的单词);
Log.v(“removewords:”,“----显示消息”);
}
public void removeWords(字符串字列表)
{
ArrayList停止列表=空;
停止名单。添加(“i”);
停止名单。添加(“拥有”);
停止名单。添加(“a”);
ArrayList结果=新的ArrayList(Arrays.asList(wordList.split)(“”));
对于(int i=0;i
输出:Headach
输出:Headach
它为您的输入返回了什么?您当前的结果是什么?字符串是不可变的。您需要从方法返回一个新字符串。如果您想从字符串中删除特定的单词,应该会帮到您。它为您的输入返回了什么?您当前的结果是什么?字符串是不可变的。您不需要o从方法中返回一个新字符串。如果要从字符串中删除特定单词,应该会有所帮助。虽然我猜这在技术上为所问问题提供了一个替代解决方案,但它的范围有限,可能对OP.@AndyPerfect correct没有太大帮助。一个更好的答案(从字符串中删除多个单词)可以。虽然我猜这在技术上为所问问题提供了一个替代解决方案,但它的范围有限,可能对OP.@AndyPerfect更正没有太大帮助。一个更好的答案(从字符串中删除多个单词)可以是。
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,"");
}