Home » Java programming language

Java String indexOf(String substr) Method with Example

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

String indexOf(String substr) Method

indexOf(String substr) is a String method in Java and it is used to get the index of a specified substring in the string.

If substring exists in the string, 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);

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.

It accepts a substring 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")

    Output:
    7

    Input: 
    String str = "IncludeHelp"

    Function call:
    str.indexOf("HELP)

    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);
        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);
        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);
        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 is found at 3 position.
HELP does not found.



Comments and Discussions!

Load comments ↻






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