Page 297 - ComputerScience_Class_11
P. 297
Program 3 Write a program to find the character at given index value.
1 import java.util.*;
2 class string_count
3 {
4 public static void main(String[] args)
5 {
6 String str= "Class 11 ISC";
7 char ch= str.charAt(2);
8 System.out.println("The character is: " +ch);
9 }
10 }
The output of the preceding program is as follows:
BlueJ: Terminal Window - Java
Options
The character is: a
The indexOf(char ch) Function
For a string variable, this function returns the index value of the first position of the given character passed as an
argument in the String object. It returns an integer type value. The syntax is:
int <variable> = String_datatype_Variable.indexOf(char ch);
Let us see the below example:
Program 4 Write a program to find the index of a character in a string.
1 class string_count
2 {
3 public static void main(String[] args)
4 {
5 String str= "Computer Science";
6 int position = str.indexOf('p');
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: 3
Strings 295

