我的目标是在名为strstr的C函数中重新创建myStrStr,如果在干草堆中找到了子字符串,则返回1;如果找不到,则返回0,所有这些都将匹配的子字符串复制到缓冲区中。

我尝试编写以下代码来解决此问题,但是我不确定为什么在编译和运行它时不会产生预期的结果。

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;
}


驱动程序代码示例如下:

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");


谢谢

最佳答案

该功能以多种方式破坏。

这是更正的版本:

int myStrStr(const char *haystack, const char *needle, char *buffer) {
    if (*needle == '\0') {
        /* special case for empty needle: return success with an empty match */
        buffer[0] = '\0';
        return 1;
    }
    for (; *haystack != '\0'; haystack++) {
        if (*haystack == *needle) {
            buffer[0] = *haystack;
            for (size_t i = 1;; i++) {
                buffer[i] = needle[i];
                if (needle[i] == '\0')
                    return 1;
                if (needle[i] != haystack[i])
                    break;
            }
        }
    }
    buffer[0] = '\0';
    return 0;
}


请注意,无需在扫描时复制匹配的字符串,找到匹配项后复制针即可。实际上,buffer的内容是一个空字符串或needle的副本:不是一个非常有用的副作用。

10-04 16:53