Java program to find the index of a specified character in a string using indexOf() method
PROGRAM:
public class IndexOfExample {public static void main(String [] args){
String s1= new String("Welcome to Java Programming");
String s2= new String("Java");
String s3= new String("Programming");
String s4= new String("hello");
System.out.println("Index of J in s1 is "+s1.indexOf('J'));
System.out.println("Index of a in s1 is "+s1.indexOf('a'));
System.out.println("Index of a in s1 after 15th char is "+s1.indexOf('a',15));
System.out.println("Index of string s2 in s1 is "+s1.indexOf(s2));
System.out.println("Index of string s3 in s1 is "+s1.indexOf(s3));
System.out.println("Index of string s4 in s1 is "+s1.indexOf(s4));
//-1 is printed since s4 is not present in s1
System.out.println("Index of string 'to' in s1 is "+s1.indexOf("to"));
}
}
OUTPUT:
Index of J in s1 is 11Index of a in s1 is 12
Index of a in s1 after 15th char is 21
Index of string s2 in s1 is 11
Index of string s3 in s1 is 16
Index of string s4 in s1 is -1
Index of string 'to' in s1 is 8