So I’m trying to make my own strstr function, with the following implemenation:
char *mystrstr(char *haystack, char *needle);
// find the first occurrence of string needle
// in string haystack
// identical to strstr in <string.h>
// running time O(mystrlen(needle)*mystrlen(haystack))
Here is what i have:
char *mystrstr(char *haystack, char *needle)
{
if (haystack == needle) { return haystack; }
int i = 0; int j = 0;
while (haystack[i] != '\0') {
if (j == mystrlen(needle)) {return haystack + (i - mystrlen(needle)); }
if (haystack [i] == needle [j]) {
j++; i++;
}
else { j = 0; i++; }
}
if (j == mystrlen(needle)) {return haystack + (i - mystrlen(needle)); }
return NULL;
}
My problem is that when i set j = 0, i dont want to iterate i. But i eventually need to iterate “i” to cause the loop to break. Any suggestions ?
Assuming you don’t want to get sophisticated (e.g., Knuth-Morris-Pratt or a Boyer-Moore variant) I think I’d do it by stepping through each possible point in the “haystack”, and comparing the N characters of the needle to the next N characters in the haystack. If they’re equal, you’ve found a position.
Edit. In pseudo-code, I’d do something like this: