Java Reference
In-Depth Information
METHOD
DESCRIPTION
Same as the preceding method, but with the search starting at position
index
in the string. If the
value of
index
is less than or equal to 0, the entire string is searched. If
index
is greater than or
equal to the length of the string, −1 is returned.
indexOf(String
str,
int index)
The four flavors of the
lastIndexOf()
method have the same parameters as the four versions of the
in-
dexOf()
method. The last occurrence of the character or substring that is sought is returned by the
lastIn-
dexOf()
method. Also because the search is from the end of the string, if
index
is less than 0, −1 is returned,
and if
index
is greater than or equal to the length of the string, the entire string is searched.
The
startsWith()
method that I mentioned earlier in the chapter also comes in a version that accepts
an additional argument that is an offset from the beginning of the string being checked. The check for the
matching character sequence then begins at that offset position. If you have defined a string as
String string1 = "The Ides of March";
then the expression
string1.startsWith("Ides", 4)
has the value
true
.
I can show the
indexOf()
and
lastIndexOf()
methods at work with substrings in an example.
TRY IT OUT: Exciting Concordance Entries
You'll use the
indexOf()
method to search the quotation you used in the last “Try It Out” example for
"and"
and the
lastIndexOf()
method to search for
"the"
.
public class FindCharacters {
public static void main(String[] args) {
// Text string to be analyzed
String text = "To be or not to be, that is the question;"
+ " Whether 'tis nobler in the mind to suffer"
+ " the slings and arrows of outrageous fortune,"
+ " or to take arms against a sea of troubles,"
+ " and by opposing end them?";
int andCount = 0;
// Number of and's
int theCount = 0;
// Number of the's
int index = -1;
// Current index position
String andStr = "and";
// Search substring
String theStr = "the";
// Search substring
// Search forwards for "and"
index = text.indexOf(andStr);
// Find first 'and'
while(index >= 0) {
++andCount;
index += andStr.length();
// Step to position after last
'and'