
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
46
|
Chapter 2: Strings and Characters
Discussion
In the example code, the foundPos variable contains the location of the found charac-
ter/string within the
searchedStr string. The startPos variable contains the next posi-
tion at which to start the search. The
IndexOf or IndexOfAny method is used to
perform the actual searching. The
count variable simply counts the number of times
the character/string was found in the
searchedStr string.
The example uses a
do loop so that the IndexOf or IndexOfAny operation is executed
at least one time before the check in the
while clause is performed. This check deter-
mines whether there are any more character/string matches to be found in the
searchedStr string. This loop terminates when foundPos returns -1 (meaning that no
more character/strings can be found in the searchedStr string) or when an out-of-
bounds condition exists. When
foundPos equals -1, there are no more instances of
the match value in the
searchedStr string; therefore, you can exit the loop. If, how-
ever, the
startPos overshoots the last character element of the searchedStr string, an
out-of-bounds condition exists and an exception is thrown. To prevent this, always
check to make sure that any positioning variables that are modified inside of the
loop, such as the
startPos variable, are within ...