Page 262 - Cs_withBlue_J_C11_Flipbook
P. 262
10.2 STRING CLASS
As explained earlier, a string is a combination of a set of characters written within double quotes. To assign a sentence
or a word to a String variable, the following syntax is used.
String (variable)= "String Literal";
For example:
String str1="Computer Science";
String str2="Kolkata – 700115";
10.2.1 Important String Methods
There are several useful String methods that come in handy while writing programs. Let us learn about them one by
one.
The length() Function
This function returns the number of characters present in a string. It returns an integer type of value. The length() is
the only function where the counting starts from 1. The syntax is:
int <variable> = String_datatype_Variable.length();
Let us see the below example:
String sub= "I am studying Computer Science ";
int len= sub.length();
System.out.println(sub + "contains " + len + " characters");
Output:
I am studying Computer Science contains 31 characters
The charAt(int index) Function
For a string variable, this function returns the character at the given index. It returns character type data. The
syntax is:
char <variable> = String_datatype_Variable.charAt(int index);
Let us see the below example:
String str= "Class 11 ISC";
char ch= str.charAt(2);
System.out.println("The character is: " +ch);
Output:
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:
String str= "Computer Science";
int position = str.indexOf('p');
System.out.println("The index value is: " + position);
Output:
The index value is: 3
260260 Touchpad Computer Science-XI

