Fetch A Word In Strings Android/Java
So I'm beginning with Android/Java programming. I want to try to find a word in a sentence. Say the user inputs in the EditText a sentence i.e. 'My friend is a cowboy.' The app sho
Solution 1:
Try the following:
String[] words = {"cowboy", "animal", "monster"};
String s = "My friend is a Cowboy";
boolean check = false;
for (int i = 0; i < words.length; i++) {
if (s.toLowerCase().contains(words[i].toLowerCase())) {
check = true;
} else {
}
}
if (check) {
System.out.println("Yes");
} else {
System.out.println("No");
}
Solution 2:
You could try iterating through your array and seeing if the base string contains all of the elements in the array. It would look something like this:
private boolean contains(final String string, final String[] strings){
for(final String s : strings)
if(!string.toLowerCase().contains(s.toLowerCase()))
return false;
return true;
}
Solution 3:
You can try this. Send from my phon so syntax errors included ;-)
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String string = text.getText().toString();
boolean hit == false;
// b = string.indexOf("cowboy") > 0;
for (int i=0;i<words.length;i++){
if (string.indexOf(words[i])!=-1){
hit == true;
break;
}
}
view.setText(b.toString());
}
});
Post a Comment for "Fetch A Word In Strings Android/Java"