How do I check if a string contains a specific word?

In this code example we are going to learn how to find a specific word or text inside a string. For this example we will utilize the java.lang.String class. The String class provides a method called String.indexOf(). It takes an argument of a String, which is the sub string that we want to find in the other string. You can imagine the sub string as a needle that we are going to find in the haystack.

If the word found more than once in the string, the indexOf() method returns the first index of a sub string found in the specified string. If the sub string can’t be found this method returns -1. The index of string returns by this method begin at zero. It means that the first letter in the string have the index number 0.

Another way that we can use is the String.contains() method. This method introduced in JDK 1.5. The method simply return a boolean value which is true or false indicating whether the string in search is found in the haystack. Let’s see the snippet below:

package org.kodejava.lang;

public class StringContainsExample {
    public static void main(String[] args) {
        String haystack = "Kodejava - Learn Java by Examples";

        // Checks to see if the word "Java" is found in the haystack
        // variable.
        String needle = "Java";
        if (haystack.indexOf(needle) != -1) {
            System.out.println("Found the word " + needle +
                    " at index number " + haystack.indexOf(needle));
        } else {
            System.out.println("Can't find " + needle);
        }

        // Or use the String.contains() method if you are not interested
        // with the index of the word.
        if (haystack.contains(needle)) {
            System.out.println("Eureka we've found Java!");
        }
    }
}

Running the example gave you the following result:

Found the word Java at index number 17
Eureka we've found Java!