Sunday, January 26, 2014

How to check if a string contains a substring?

Source:
public class TestSubString {
   public static void main(String[] args) {
      String str = "Do you like green eggs and ham";
      System.out.println(str);

      // indexOf() returns the index within this string of the first 
      // occurrence of the specified substring.
      int i = str.indexOf("green eggs");
      System.out.println("Index: " + i );

      // indexOf() returns -1 if not found
      i = str.indexOf("yellow eggs");
      System.out.println("Index: " + i );
   }
}

Output:
   $ java TestSubString 
   Do you like green eggs and ham
   Index: 12
   Index: -1

Blog Archive