Bruteforce strstr() implementation
There are many fancy algorithms worth studying. This is just my naive, sub-optimal, bruteforce Friday evening implementation.
#include <stdio.h>
#include <string.h>
int strStr(char* haystack, char* needle)
{
// return value
int pos = 0;
// save the beginning of the needle
char *nee = needle;
// haystack offset
int goBack = 0;
// save these for performance
int haylen = strlen(haystack);
int neelen = strlen(needle);
// edge cases
if (haylen == 0 && neelen == 0) return 0;
if (neelen == 0) return 0;
// bruteforce
while (*haystack) {
while (*haystack++ == *needle++) {
goBack++;
if (*needle == '\0') return pos;
}
haystack -= goBack;
goBack = 0;
needle = nee;
pos++;
// performance boost
if ( (haylen - pos) < neelen ) return -1;
}
return -1;
}