-
-
Save kavinyao/4014994 to your computer and use it in GitHub Desktop.
strstr
This file contains hidden or 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
#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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This version compiles with
gcc -Wall -Werror