Java program to find the index of a particular character in a given string


Following program shows you how to find the index of a particular character in a given string.

import java.util.Scanner;

public class StringOperations9 {

   public static void main(String[] args) {

   	String input;

   	Scanner in = new Scanner(System.in);

   	System.out.println("Please enter a string:");

   	input = in.nextLine();

   	System.out.println("Please enter a character:");

   	String character = in.nextLine();

   	System.out.println("Index of given character is: " + input.indexOf(character));
   }
}

Output:

Example1:

Please enter a string:
hello
Please enter a character:
o
Index of given character is: 4

Example2:

Please enter a string:
hello
Please enter a character:
r
Index of given character is: -1