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:
The lastIndexOf( ) method has four forms:
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:
To search for the last occurrence of a character or a substring use the first and third form of lastIndexOf method. For example:
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:
For lastIndexOf( ), the search runs from specific index to zero. For example:
Program
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)); } }