Home » Java programming language

Java String indexOf(String substr, int fromIndex) Method with Example

Java String indexOf(String substr, int fromIndex) Method: Here, we are going to learn about the indexOf(String substr, int fromIndex) method with example in Java.
Submitted by IncludeHelp, on February 20, 2019

String indexOf(String substr, int fromIndex) Method

indexOf(String substr, int fromIndex) is a String method in Java and it is used to get the index of a specified substring in the string from given fromIndex. That means to search for the substring will start from the given index (fromIndex).

If substring exists in the string from fromIndex, it returns the index of the first occurrence of the substring, if substring does not exist in the string, it returns -1.

Syntax:

    int str_object.indexOf(String substr, int fromIndex);

Here,

  • str_object is an object of main string in which we have to find the index of given substring.
  • substr is the part of the string to be found in the string.
  • fromIndex is an index of the main string, from where method will start searching for the substring.

It accepts a substring, from index and returns index of its first occurrence or -1 if substring does not exist in the string.

Example:

    Input: 
    String str = "IncludeHelp"

    Function call:
    str.indexOf("Help", 4)

    Output:
    7

    Input: 
    String str = "IncludeHelp"

    Function call:
    str.indexOf("HELP, 2)

    Output:
    -1

Java code to demonstrate the example of String.indexOf() method

public class Main
{
    public static void main(String[] args) {
        String str = "IncludeHelp";
        String substr = "";
        int index;
        
        substr = "Help";
        index = str.indexOf(substr, 4);
        if(index != -1)
            System.out.println(substr + " is found at " + index + " position.");
        else 
            System.out.println(substr + " does not found.");

        substr = "lude";
        index = str.indexOf(substr, 8);
        if(index != -1)
            System.out.println(substr + " is found at " + index + " position.");
        else 
            System.out.println(substr + " does not found.");            

        substr = "HELP";
        index = str.indexOf(substr, 2);
        if(index != -1)
            System.out.println(substr + " is found at " + index + " position.");
        else 
            System.out.println(substr + " does not found.");
    }
}

Output

Help is found at 7 position.
lude does not found.
HELP does not found.


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.