Page 298 - ComputerScience_Class_11
P. 298
The indexOf(char ch, int index) Function
For a string variable, this function returns the index value of the given character present in the string of the current
String object starting from the index provided in the parameter. It returns an integer type value. The syntax is:
int <variable> = String_datatype_Variable.indexOf(char ch, int index);
Let us see the below example:
Program 5 Write a program to find the index of the character ‘c’ in the string “Computer Science”,
starting from position 11.
1 class string_count
2 {
3 public static void main(String[] args)
4 {
5 String str= "Computer Science";
6 int position= str.indexOf('c',11);
7 System.out.println("The index value is: " + position);
8 }
9 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
The index value is: 14
The lastIndexOf(char ch) Function
For a string variable, this function returns the index value of the last existence of the given character present in the
string of the current String object. It returns an integer type value. The syntax is:
int <variable> = String_datatype_Variable.lastIndexOf(char ch);
Let us see the below example:
Program 6 Write a program to find the last index of the character ‘e’ in the string “Computer Science”.
1 class string_count
2 {
3 public static void main(String[] args)
4 {
5 String str= "Computer Science";
6 int position= str.lastIndexOf('e');
7 System.out.println("The index value is: " +position);
8 }
9 }
296 Touchpad Computer Science (Ver. 3.0)-XI

