Skip to content

Instantly share code, notes, and snippets.

@clippit
Created November 4, 2012 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save clippit/4012541 to your computer and use it in GitHub Desktop.
Save clippit/4012541 to your computer and use it in GitHub Desktop.
strstr
char* my_strstr(const char* haystack, const char* needle) {
if (!*needle)
return haystack;
char* h = haystack;
char* n = needle;
int found = 0;
while (*h) {
char* hp = h;
while (*hp && *n && *hp == *n) {
n++;
hp++;
}
if (*n == '\0')
return h;
if (*hp == '\0')
return NULL;
h++;
}
return NULL;
}
char * print_helper(char* str) {
if (str != NULL)
return str;
else
return "NULL";
}
int main() {
char *haystack = "abcdefghijklmn";
printf("%s\n", print_helper(my_strstr(haystack, "abc")));
printf("%s\n", print_helper(my_strstr(haystack, "gh")));
printf("%s\n", print_helper(my_strstr(haystack, "n")));
printf("%s\n", print_helper(my_strstr(haystack, "")));
printf("%s\n", print_helper(my_strstr(haystack, "zzz")));
printf("%s\n", print_helper(my_strstr(haystack, "mnop")));
return 0;
}
@clippit
Copy link
Author

clippit commented Nov 4, 2012

Output:

abcdefghijklmn
ghijklmn
n
abcdefghijklmn
NULL
NULL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment