So how do you check if a string has a particular word in it?
So this is my code:
a.setOnClickListener(new View.OnClickListener() {
@Overri
Maybe this post is old, but I came across it and used the "wrong" usage. The best way to find a keyword is using .contains
, example:
if ( d.contains("hello")) {
System.out.println("I found the keyword");
}
Not as complicated as they say, check this you will not regret.
String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";
if ( sentence.toLowerCase().indexOf(search.toLowerCase()) != -1 ) {
System.out.println("I found the keyword");
} else {
System.out.println("not found");
}
You can change the toLowerCase()
if you want.
The other answer (to date) appear to check for substrings rather than words. Major difference.
With the help of this article, I have created this simple method:
static boolean containsWord(String mainString, String word) {
Pattern pattern = Pattern.compile("\\b" + word + "\\b", Pattern.CASE_INSENSITIVE); // "\\b" represents any word boundary.
Matcher matcher = pattern.matcher(mainString);
return matcher.find();
}
.contains()
is perfectly valid and a good way to check.
(http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#contains(java.lang.CharSequence))
Since you didn't post the error, I guess d
is either null or you are getting the "Cannot refer to a non-final variable inside an inner class defined in a different method" error.
To make sure it's not null, first check for null in the if statement. If it's the other error, make sure d
is declared as final
or is a member variable of your class. Ditto for c
.