c - 不使用内置函数的字符串搜索 C 程序

标签 c

我的 C 程序有问题。这是字符串搜索程序。问题是当我键入字符串 aabaaacaamaad 时,当我在其中搜索 ab 时结果为 NULL 但它不应该是 abaabaaacaamaad 中。同样的结果也出现在 amad 上,这是正确的,但为什么它出现在 aabaaacaamaad 上?代码:

char* MyStrstr(char* pszSearchString, char* pszSearchWord);
int main(int argc, char* argv[])
{
    char szTemp1[20] = {0};
    char szTemp2[10] = {0};
    char * pszTemp1 = NULL;
    strcpy(szTemp1, "aabaaacaamaad");
    strcpy(szTemp2, "aa");

    pszTemp1 = MyStrstr(szTemp1, szTemp2);
    printf("%s", pszTemp1);
    getch();
    return 0;
}

char* MyStrstr(char* pszSearchString, char* pszSearchWord) 
{
    int nFcount = 0;                    
    int nScount = 0;                    
    int nSearchLen = 0;
    int nIndex = 0;
    char* pszDelString = NULL; 

    if(pszSearchString == NULL || pszSearchWord == NULL) {
    return NULL;
    }   

    while(pszSearchWord[nSearchLen] != '\0') {
        nSearchLen++;
    }                       
    if(nSearchLen <= 0){
        return pszSearchString;
    }

    for(nFcount = 0; pszSearchString[nFcount] != '\0'; nFcount++) {
        if(pszSearchString[nFcount] == pszSearchWord[nScount]) {
           nScount++;
        } else {
           nScount = 0;
        }  

        if(nScount == nSearchLen) {
            nIndex = (nFcount - nScount) + 1;
            pszDelString = pszSearchString + nIndex;
            return pszDelString;
        }
   }
   return NULL;
}

最佳答案

我看到您的代码试图做什么,您想避免一个循环中的一个循环,但是您遗漏了一件事。当匹配失败时,您不会返回,但仍会在 pszSearchString 中继续前进,而您不应该这样做。这个缺陷的结果是在不完全匹配的情况下你会跳过字符。这就是为什么 strstr 函数最初在循环中使用循环的原因,因此对于 pszSearchString 中的每个字符都有一个新的循环来匹配 pszSearchWord。这是来自 BSD/Darwin 的原始 strstr.c 文件:

char * strstr(const char *in, const char *str)
{
    char c;
    size_t len;

    c = *str++;
    if (!c)
        return (char *) in; // Trivial empty string case

    len = strlen(str);
    do {
        char sc;

        do {
            sc = *in++;
            if (!sc)
                return (char *) 0;
        } while (sc != c);
    } while (strncmp(in, str, len) != 0);

    return (char *) (in - 1);
}

关于c - 不使用内置函数的字符串搜索 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23057013/

相关文章:

c - 运行时错误 sigsegv

c - 为什么 main 函数总是要返回一些东西?

c - Ubuntu 上的 makefile 问题

c - 如何阻塞信号量直到其值为正数

c - 想要打印给定数组中具有相同数字的数组元素,例如 2222、11、888888 等。 {1, 121,222,44,451,5510,414}

python - 读取文本列的大型数据文件的最快方法是什么?

c - 数据包中的字符串搜索

c - 是否必须尽可能对三元运算符进行静态评估?

c - GCC 以双机器字类型(包括 asm)访问高/低机器字

java - 指向java中等效指针的指针