When I had startIndex++
in the last line of the while loop it caused an infinite loop, but using startIndex +
1, the program worked fine. I was wondering why this is so?
public static int numOccurrences(String src, String q) {
int startIndex = src.indexOf(q);
int counter = 0;
while (startIndex != -1) {
counter++;
startIndex = src.indexOf(q, startIndex + 1);
}
return counter;
}
Consider what happens - if indexOf
fails, it returns -1
. If you had a blind startIndex++
after that, then your startIndex would become 0
, the loop would wrap around, and 0 != -1
is TRUE, continuing the loop. You'd get another -1
, increment it to 0
, and around and around you go - search, fail, increment, loop/repeat.
The expression startIndex++
increments the value of the variable startIndex
, but it returns the old value of startIndex
. After evaluating the expression which contains startIndex++
you assign the result to startIndex
. That means that in your case that increment is discarded and startIndex++
and startIndex
will have the exact same result: the same occurrence will be found each time, and you have an infinite loop.
The expression startIndex + 1
, on the other hand, does not change the value of startIndex
, but evaluates to the integer following the value of startIndex
. Now the indexOf
starts searching after the found occurrence, so you do not have an infinite loop.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.