How to check whether a String contains a substring or not?

Java 8Object Oriented ProgrammingProgramming

This example shows how we can search a word within a String object using indexOf() method which returns a position index of a word within the string if found. Otherwise, it returns -1. 

Example

public class SearchStringEmp {
   public static void main(String[] args) {
      String strOrig = "Hello readers"; int intIndex = strOrig.indexOf("Hello"); if(intIndex == - 1) {
         System.out.println("Hello not found");
      } else {
         System.out.println("Found Hello at index " + intIndex);
      }
   }
}

Output

The above code sample will produce the following result. 

Found Hello at index 0
raja
Published on 06-Feb-2018 12:12:19
Advertisements