Reputation: 27
To stop the loop foundAtPosition
needs to be equal to -1
how is that ?
var myString = "Welcome to Wrox books. ";
myString = myString + "The Wrox website is www.wrox.com. ";
myString = myString + "Visit the Wrox website today. Thanks for buying Wrox";
var foundAtPosition = 0;
var wroxCount = 0;
while (foundAtPosition != -1) {
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
if (foundAtPosition != -1) {
wroxCount++;
foundAtPosition++;
}
}
document.write("There are " + wroxCount + " occurrences of the word Wrox");
Upvotes: 0
Views: 70
Reputation: 33726
The key relies on these two lines
- This line
|
v
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
if (foundAtPosition != -1) {
wroxCount++;
foundAtPosition++; <- And this line
}
The algorithm is moving through the positions of your String:
For example:
var phrase = "The Wrox website is www.wrox.com." <- Iteration [1]
^
|_ First occurence at position [4] -> foundAtPosition++ = 5 -> wroxCount = 1
"The Wrox website is www.wrox.com." <- Iteration [2] -> The algorithm won't find the word because the `indexOf` function finds the index from position [5] til `phrase.length`.
^
|_ No more occurences, therefore, foundAtPosition = -1
Result: wroxCount === 1
Upvotes: 0
Reputation: 68423
i don't understand why is this loop not infinit
It will be infinite if you don't pass the second parameter foundAtPosition
foundAtPosition = myString.indexOf("Wrox", foundAtPosition);
But since you passed this parameter, second time onwards it will look from (after this foundAtPosition
index) and eventually it will have -1
Upvotes: 1
Reputation: 2227
while
loop is executing while is condition evaluated as true. indexOf
returns index -1 when given word is not found in string.
Upvotes: 0