How to check String contains a text in Java? contains() and indexOf() Example

Sometimes you want to check if one String contains another String or SubString or not e.g. "HelloWorld" contains "Hello" and "World" SubString. There are many ways to check SubString in String in Java e.g. contains(), indexOf(), or matches() method of java.lang.String class. In the last article, we have seen how to use matches method of String class with a regular expression and In this article we will see example of contains() and indexOf() method to check any String or SubString in Java. 

Both contains() and indexOf method is defined in java.lang.String class and used to check if String contains a particular SubString or not, only difference between contains() and indexOf() method is that, contains is added in Java 5 along with String matches() method while indexOf() is as old as equals(), hashCode and compareTo().

Another difference between contains() and indexOf() method is that contains() return boolean value e.g. true if String contains SubString and false if String doesn't contain SubString but indexOf() return int value, which is actually an index of SubString like starting location. indexOf() return -1 if source String does not contain SubString in Java.



String contains() and indexOf() Example in Java

Let's see one quick example of how to use contains() and indexOf() method of the Java String class. Here we will use them to check if String contains a particular SubString or not.

In this Java program we have used String "Hello World" and checking for words "Hello" and "World" in this String. You can also see these Java Programming courses to learn more about fundamental Java concepts like String. 

How to check String contains a text in Java? contains() and indexOf() Example

And here is our code to show how to use these two common String methods in Java:

/**
 *
 * Java program to check String for SubString. This program
 * demonstrate two ways to find if One String
 * contains a particular word or not in Java.
 * contains() and indexOf() method of String class
 *  is used to check SubString
 * @author
 */

public class StringContainsExample {

 
    public static void main(String args[]) {

       String word = "Hello World";
     
       //indexOf return -1 if String does not contain a specified word
       if(word.indexOf("World") != -1){
           System.err.printf("Yes '%s' contains
                  word 'World' %n"
, word);
       }else{
           System.err.printf("Sorry %s does not contains
                 word 'World' %n "
, word);
       }
     
       //contains method return boolean true if String
      // contains the specified word

       if(word.contains("Hello")){
           System.err.printf("Great '%s' contains
             word 'Hello' %n"
, word);
       }else{
           System.err.printf("Sorry %s does not
             contains word 'Hello' %n"
, word);
       }
     
    }
}

Output:
Yes 'Hello World' contains the word 'World'
Great 'Hello World' contains the word 'Hello'

If we re-run this Java program again with different input e.g. checking for Helloo or World SubString which is not in original The string, you will receive different output. 

By the way, another difference between contains() and indexOf() methods is that contains() accept a CharSequence object as the parameter which is a super interface for String, StringBuffer and StringBuilder in Java. You can pass either of those objects to contains() method in Java.

These are two quick ways to check if one String contains another String, Character, or Substring or not, which is a very common programming question in Java interviews, along with how to compare two String in Java or how to split String in Java.


Other String articles in Java you may find useful:

There are a lot of changes in Java API from Java 1.5 to Java 1.5 and it's still worth exploring. That's all on String contains() example and String indexOf() example in Java.

And now one question is for you? What will happen if you call the substring method on a String which is null and empty? 

8 comments:

  1. how to check sentence "demonstrate two ways to find if One String contains a particular word or not in Java" contain a word in list {"two", "ways", "one" ,"not"}

    ReplyDelete
  2. How to count the repetition for a particular word in a paragraph?

    ReplyDelete
    Replies
    1. int i,count=0;
      int LengthOfString=word.length();

      for(i=0;i<=LengthOfString;i++)

      {
      if(word.indexOf("World") != -1)
      {

      count=count+1;
      }

      }
      System.out.println("Total Repetitions are : "+ count)

      Delete
  3. Nossir.

    this will be true every time it loops regardless of the number of times the word appears, meaning your count will just equal the length of your string.

    ReplyDelete
  4. How to code if, one word is equal to one index.
    Ex: Hello I am World
    Search Word: am
    Index: the index should be 2, not 8.

    ReplyDelete
    Replies
    1. You need to code your own method which will first split the string an create an array of words and then serach. /Alternatively, just split the string and insert into HashMap then serach

      Delete
  5. How to list of Strings and shifts them all, returning the entire list of lines

    ReplyDelete

Feel free to comment, ask questions if you have any doubt.