Skip to Content

Java Search String using indexOf Example

  1. /*
  2.   Java Search String using indexOf Example
  3.   This example shows how we can search a word within a String object using
  4.   indexOf method.
  5. */
  6.  
  7. public class SearchStringExample {
  8.  
  9.   public static void main(String[] args) {
  10.     //declare a String object
  11.     String strOrig = "Hello world Hello World";
  12.    
  13.     /*
  14.       To search a particular word in a given string use indexOf method.
  15.       indexOf method. It returns a position index of a word within the string
  16.       if found. Otherwise it returns -1.
  17.     */
  18.    
  19.     int intIndex = strOrig.indexOf("Hello");
  20.    
  21.     if(intIndex == - 1){
  22.       System.out.println("Hello not found");
  23.     }else{
  24.       System.out.println("Found Hello at index " + intIndex);      
  25.     }
  26.    
  27.     /*
  28.       we can also search a word after particular position using
  29.       indexOf(String word, int position) method.  
  30.     */
  31.    
  32.     int positionIndex = strOrig.indexOf("Hello",11);
  33.     System.out.println("Index of Hello after 11 is " + positionIndex);
  34.    
  35.     /*
  36.       Use lastIndexOf method to search a last occurrence of a word within string.
  37.     */
  38.     int lastIndex = strOrig.lastIndexOf("Hello");
  39.     System.out.println("Last occurrence of Hello is at index " + lastIndex);
  40.  
  41.   }
  42. }
  43.  
  44. /*
  45. Output of the program would be :
  46. Found Hello at index 0
  47. Index of Hello after 11 is 12
  48. Last occurrence of Hello is at index 12
  49. */