My goal is to recreate strstr
in a C function named myStrStr
that returns a 1
if the substring is found in the haystack and a 0
if it is not, all while copying the matched substring into a buffer.
I tried writing the following code to solve this, and I'm unsure of why it doesn't produce the desired result when it is compiled and run.
int myStrStr(char *haystack, char *needle, char *buffer) {
int i = 1;
char *k = (haystack + i);
for (; *haystack != '\0'; haystack++) {
if (*haystack == *needle) {
buffer[0] = *haystack;
for (; *needle != '\0'; needle++) {
if (*needle = *k) {
buffer[i] = *k;
i++;
printf("%d\n", i);
} else
if (strlen(buffer) == strlen(needle)) {
return 1;
} else {
buffer[0] = 0;
}
}
}
}
return 0;
}
an example of the driver code is as follows:
int myStrStr(char[], char[], char[]);
char haystack[][20] = { "chocolate", "vanilla", "caramel", "strawberry", "banana", "cherry" };
char needle[][20] = { "choc", "lla", "am", "strawberry", "na", "terrible" };
char buffer[255];
printf("\n\t=========Test #1: myStrStr with '%s' and substring '%s'===========\n\n", haystack[0], needle[0]);
int result = myStrStr(haystack[0],needle[0],buffer);
assert(result == 1&& strcmp(needle[0], buffer) == 0);
printf("\n\t\t....Test Passed\n");
printf("\n\t=========Test #2: myStrStr with '%s' and substring '%s'===========\n\n", haystack[1], needle[1]);
result = myStrStr(haystack[1],needle[1],buffer);
assert(result == 1 && strcmp(needle[1], buffer) == 0);
printf("\n\t\t....Test Passed\n");
Thanks