我的 C 程序有问题。这是字符串搜索程序。问题是当我键入字符串 aabaaacaamaad
时,当我在其中搜索 ab
时结果为 NULL
但它不应该是 ab
在 aabaaacaamaad
中。同样的结果也出现在 am
和 ad
上,这是正确的,但为什么它出现在 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/