Get Specific Index

Java-Get Specific Index

Get Specific Index

The String class provides two methods, indexOf( ) and lastIndexOf( ), that allows you to get index of a specified character or starting index of the specified substring. The indexof() method has four forms:

Get Specific Index

The lastIndexOf( ) method has four forms:

Get Specific Index

These all methods return the index at which the character or substring was found, or –1 on failure. To search for the first occurrence of a character or a substring use the first and third form of indexOf method. For example:

Get Specific Index

To search for the last occurrence of a character or a substring use the first and third form of lastIndexOf method. For example:

Get Specific Index

If you want to search from specific index use the second and fourth form of indexOf() and lastIndexOf(). For indexOf( ), the search runs from specific index to the end of the string. For example:

Get Specific Index

For lastIndexOf( ), the search runs from specific index to zero. For example:

Get Specific Index

Program

Get Specific Index

Program Source

public class Javaapp {

    public static void main(String[] args) {

        String str = "ABCDEABCDE";

        System.out.println("indexOf -> "+str.indexOf("BC"));
        
        System.out.println("indexOf -> "+str.indexOf("BC",5));
        
        System.out.println("lastIndexOf -> "+str.lastIndexOf("BC"));
        
        System.out.println("lastIndexOf -> "+str.lastIndexOf("BC",5));
    }
}

Leave a Comment