Java Reference
In-Depth Information
System.out.println("The text contains " + andCount + " ands\n"
+ "The text contains " + theCount + " thes");
}
}
The program will produce the output:
The text contains 2 ands
The text contains 5 thes
If you were expecting the " the " count to be 3, note that there is one instance 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 either side
of the " the " substring.
How It Works
We define the String variable, text , as before, and set up two counters, andCount and theCount ,
for the two words. The variable index will keep track of the current position in the string. We then
have String variables andStr and theStr holding the substrings we will be searching for.
To find the instances of " and ", we 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 will not
execute as the condition is false on the first iteration. Assuming there is at least one " and ", the while
loop block is executed and andCount is incremented for the instance of " and " we have just found. The
method indexOf() returns the index position of the first character of the substring, so we have to
move the index forward to the character following the last character of the substring we have just found.
This is done by adding the length of the substring, as shown in the following diagram:
Search WWH ::




Custom Search