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

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.