Created
November 4, 2012 16:41
-
-
Save clippit/4012541 to your computer and use it in GitHub Desktop.
strstr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: