The
String
class provides 2 methods for searching a
string
. They are :
-
indexOf()
: Searches for the first occurrence of a character or substring.
-
lastIndexOf()
: Searches for the last occurrence of a character or substring.
These methods return the starting index of character or a substring on a successful search else they return
-1
.
There are many overloaded forms of these methods:
This example program elaborates these methods.
SearchingStrings
class StringSearchDemo
{
public static void main(String arg[])
{
String str = "The Sun rises in the east and sets in the west.";
System.out.println("Length of str : " + str.length());
System.out.println("indexOf(i) : " + str.indexOf('i')); // LINE A
System.out.println("lastIndexOf(i) : " + str.lastIndexOf('i')); // LINE B
System.out.println("indexOf(st) : " + str.indexOf("st")); // LINE C
System.out.println("lastIndexOf(st) : " + str.lastIndexOf("st")); // LINE D
System.out.println("indexOf(e, 2) : " + str.indexOf('e', 2)); // LINE E
System.out.println("lastIndexOf(e, 46) : " + str.lastIndexOf('e', 46)); // LINE F
System.out.println("indexOf(st, 2) : " + str.indexOf("st", 2)); // LINE G
System.out.println("lastIndexOf(st, 46) : " + str.lastIndexOf("st", 46)); // LINE H
}
}
OUTPUTLength of str : 47
indexOf(i) : 9
lastIndexOf(i) : 35
indexOf(st) : 23
lastIndexOf(st) : 44
indexOf(e, 2) : 2
lastIndexOf(e, 46) : 43
indexOf(st, 2) : 23
lastIndexOf(st, 46) : 44
DESCRIPTIONLINE A
is the display of index of first occurrence of character 'i
'. LINE B
is the display of index of last occurrence of character 'i
'. LINE C
is the display of index of first occurrence of substring "st
". LINE D
is the display of index of last occurrence of substring "st
".
LINE E
is the display of index of first occurrence of character 'e
' while the search starts at index 2
and continues till the end of String str
. LINE F
is the display of index of first occurrence of character 'e
' while the search runs from index 46
to zero
of String str
.
LINE G
is the display of index of first occurrence of substring "st
" while the search starts at index 2
and continues till the end of String str
. LINE H
is the display of index of first occurrence of substring "st
" while the search runs from index 46
to zero
of String str
.