indexOf():
This method is used to search a character or a string within the string.
This method is used to search a character or a string within the string.
There are two
forms of this function:
indexOf(int
ch)
indexOf(String
s)
Where:
ch specify the ASCII value of the character which we want to
search
s will be the substring which you
want to search
The function
returns the index number of the first match and if no match occurs then the
method will return -1
Example:
String s="this is the
very fine day";
System.out.println(s.indexOf('t'));
System.out.println(s.indexOf("that"));
System.out.println(s.indexOf("the"));
Output :
0
-1
8
There is another
form also which can be used for searching the multiple occurrences of a single
character or a string.
indexOf(int ch,int sindex)
indexOf(String s,int sindex)
Where:
sindex
specify the index position from where we want to start the searching
Example:
String s="this is a
matrix . this is cool";
System.out.println(s.indexOf("this"));
System.out.println(s.indexOf("this",0));
System.out.println(s.indexOf("this",2));
Output:
0
0
18
Comments
Post a Comment