Java Reference
In-Depth Information
index = text.indexOf(andStr, index);
}
// Search backwards for "the"
index = text.lastIndexOf(theStr); // Find last 'the'
while(index >= 0) {
++theCount;
index -= theStr.length();
// Step to position before
last 'the'
index = text.lastIndexOf(theStr, index);
}
System.out.println("The text contains " + andCount + " ands\n"
+ "The text contains " + theCount + " thes");
}
FindCharacters.java
The program produces the following output:
The text contains 2 ands
The text contains 5 thes
NOTE
Ifyouwereexpecting the
"the"
counttobe3,notethatthereisoneinstance
in
"whether"
and another in
"them"
. If you want to find three, you need to refine
your program to eliminate such pseudo-occurrences by checking the characters on
either side of the
"the"
substring.
How It Works
You define the
String
variable,
text
, as before, and set up two counters,
andCount
and
theCount
, for
the two words. The variable
index
keeps track of the current position in the string. You then have
String
variables
andStr
and
theStr
holding the substrings you will be searching for.
To find the instances of
"and"
, you first find the index position of the first occurrence of
"and"
in the
string
text
. If this index is negative,
text
does not contain
"and"
, and the
while
loop does not execute,
as the condition is
false
on the first iteration. Assuming there is at least one
"and"
, the
while
loop block
executes and
andCount
is incremented for the instance of
"and"
you have just found. The
indexOf()
method returns the index position of the first character of the substring, so you have to move the index
forward to the character following the last character of the substring you have just found. This is done by
adding the length of the substring, as shown in
Figure 4-11
.