Find Index Of A Particular String Example Java Program

Definition

This method indexOf() is an inbuilt method of strings which is used to find the index of a particular character or string.

Syntax

int indexOf(String str)

Find Index Of A Particular String Example Program

import java.util.Scanner;

class FindIndexOfString { 
	public static void main(String args[]) { 
		Scanner in=new Scanner(System.in);
		String str1="";
		String str2 = "Hard work pays"; 
		System.out.println(str2); 
		System.out.print("Enter the character for which the index is to be found: ");
		str1=in.next();
		System.out.println("index Of the character is " +str2.indexOf(str1));  
	}
}

Sample Output

Output is:
Hard work pays
Enter the character for which the index is to be found: pays
index Of the character is 10