[java] To check if string contains particular word

So how do you check if a string has a particular word in it?

So this is my code:

a.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            if(d.contains("Hey")){
                c.setText("OUTPUT: SUCCESS!"); 
            }else{
                c.setText("OUTPUT: FAIL!");  
            }
        }
    });

I'm getting an error.

This question is related to java android

The answer is


if (someString.indexOf("Hey")>=0) 
     doSomething();

You can use regular expressions:

if (d.matches(".*Hey.*")) {
    c.setText("OUTPUT: SUCCESS!");
} else {
    c.setText("OUTPUT: FAIL!");  
}

.* -> 0 or more of any characters

Hey -> The string you want

If you will be checking this often, it is better to compile the regular expression in a Pattern object and reuse the Pattern instance to do the checking.

private static final Pattern HEYPATTERN = Pattern.compile(".*Hey.*");
[...]
if (HEYPATTERN.matcher(d).matches()) {
    c.setText("OUTPUT: SUCCESS!");
} else {
    c.setText("OUTPUT: FAIL!");  
}

Just note this will also match "Heyburg" for example since you didn't specify you're searching for "Hey" as an independent word. If you only want to match Hey as a word, you need to change the regex to .*\\bHey\\b.*


Using contains

String sentence = "Check this answer and you can find the keyword with this code";
String search = "keyword";

if (sentence.toLowerCase().contains(search.toLowerCase())) {

  System.out.println("I found the keyword..!");

} else {

  System.out.println("not found..!");

}

Solution-1: - If you want to search for a combination of characters or an independent word from a sentence.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".*Beneficent.*")) {return true;}
else{return false;}

Solution-2: - There is another possibility you want to search for an independent word from a sentence then Solution-1 will also return true if you searched a word exists in any other word. For example, If you will search cent from a sentence containing this word ** Beneficent** then Solution-1 will return true. For this remember to add space in your regular expression.

String sentence = "In the Name of Allah, the Most Beneficent, the Most Merciful."
if (sentence.matches(".* cent .*")) {return true;}
else{return false;}

Now in Solution-2 it wll return false because no independent cent word exist.

Additional: You can add or remove space on either side in 2nd solution according to your requirements.


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();
}

It's been correctly pointed out above that finding a given word in a sentence is not the same as finding the charsequence, and can be done as follows if you don't want to mess around with regular expressions.

boolean checkWordExistence(String word, String sentence) {
    if (sentence.contains(word)) {
        int start = sentence.indexOf(word);
        int end = start + word.length();

        boolean valid_left = ((start == 0) || (sentence.charAt(start - 1) == ' '));
        boolean valid_right = ((end == sentence.length()) || (sentence.charAt(end) == ' '));

        return valid_left && valid_right;
    }
    return false;
}

Output:

checkWordExistence("the", "the earth is our planet"); true
checkWordExistence("ear", "the earth is our planet"); false
checkWordExistence("earth", "the earth is our planet"); true

P.S Make sure you have filtered out any commas or full stops beforehand.


.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.


   String sentence = "Check this answer and you can find the keyword with this code";
    String search = "keyword";

Compare the line of string in given string

if ((sentence.toLowerCase().trim()).equals(search.toLowerCase().trim())) {
System.out.println("not found");
}
else {  
    System.out.println("I found the keyword"); 
} 

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");
}