Java.lang.String.indexOf() Method



Description

The java.lang.String.indexOf(String str, int fromIndex) method returns the index within this string of the first occurrence of the specified substring, starting at the specified index. The integer returned is the smallest value k for which −

k > = Math.min(fromIndex, this.length()) && this.startsWith(str, k)

If no such value of k exists, then -1 is returned. .

Declaration

Following is the declaration for java.lang.String.indexOf() method

public int indexOf(String str, int fromIndex)

Parameters

  • str − This is the substring for which to search.

  • fromIndex − This is the index from which to start the search.

Return Value

This method returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

Exception

NA

Example

The following example shows the usage of java.lang.String.indexOf() method.

package com.tutorialspoint;

import java.lang.*;

public class StringDemo {

   public static void main(String[] args) {

      String str1 = "Collections of tutorials at tutorials point";
     
      /*  search starts from index 10 and if located it returns 
         the index of the first character of the substring "tutorials" */
      System.out.println("index = " + str1.indexOf("tutorials", 10)); 
      
      /* search starts from index 9 and returns -1 as substring "admin"
         is not located */
      System.out.println("index = " + str1.indexOf("admin", 9));     
   }
}

Let us compile and run the above program, this will produce the following result −

index = 15
index = -1
java_lang_string.htm
Advertisements