Skip to content

Instantly share code, notes, and snippets.

@kavinyao
Forked from clippit/gist:4012541
Created November 5, 2012 02:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kavinyao/4014994 to your computer and use it in GitHub Desktop.
Save kavinyao/4014994 to your computer and use it in GitHub Desktop.
strstr
#include <stdio.h>
const char* my_strstr(const char* haystack, const char* needle) {
if (!*needle)
return haystack;
const char* h = haystack;
const char* n = needle;
while (*h) {
const char* hp = h;
while (*hp && *n && *hp == *n) {
n++;
hp++;
}
if (*n == '\0')
return h;
if (*hp == '\0')
return NULL;
h++;
}
return NULL;
}
const char * print_helper(const 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;
}
@kavinyao
Copy link
Author

kavinyao commented Nov 5, 2012

This version compiles with gcc -Wall -Werror

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