Originally Posted by
whiteflags
Tabstop, I have to say, that post makes no sense. What we are arguing is basically a working implementation of strstr() written in terms of strchr() and strncmp().
The call: i = haystack.find(needle[0], i) is made, which searches starting at 0, but may search next time at 5 or what have you, depending on the return value of the previous call to find(). The reason we update i by one is so that we start find() at the earliest possible position you could expect needle[0] to be again, upon the next iteration. If we take the very first use of find as an example: say find(needle[0], 0) returns 4, so on the next call to find it will be find(needle[0], 5). The condition of the loop itself is i != npos. So, what will happen instead of stepping through the entire string is that find() will search for needle[0] in smaller and smaller substrings of haystack. When it can't find needle[0] anywhere the result is a failed search. Stepping through haystack is really not part of the algorithm.
Further, I do not fiddle with i in your check-the-rest-of-the-substring part. By that time, i is the current result of find(), and a purposeful and correct comparison will be made to see if the wanted substring, needle, starts at haystack[i].