【问题标题】:Showing line of text file without using strstr() in C在 C 中不使用 strstr() 显示文本文件行
【发布时间】:2014-04-09 11:38:46
【问题描述】:

我的 C 程序有问题。它是从文本文件中搜索字符串并输出以用户输入字符开头的行而不使用 strstr() 的命令行参数。没关系,但有一个问题。当搜索字符为空时,我想输出整个文件。当我这样做时,使用 strstr() 内置函数的输出变得不同。你能帮我看看我的代码有什么问题吗?

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char* MyStrstr(char* pszSearchString, char* pszSearchWord);

int main(int argc, char* argv[])
{
    char szTemp1[10] = {0};
char szTemp2[10] = {0};
char * pszTemp1 = NULL;
char * pszTemp2 = NULL;

strcpy(szTemp1, "aabaaacaaaad");
strcpy(szTemp2, "");

pszTemp1 = MyStrstr(szTemp1, szTemp2);
pszTemp2 = strstr(szTemp1, szTemp2);
printf("%s\n",pszTemp1);
printf("%s", pszTemp2);

    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) {
    return NULL;
}
if(pszSearchWord == ""){
    return pszSearchString;
} else {
    while(pszSearchWord[nSearchLen] != '\0') {
        nSearchLen++;
    }

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

【问题讨论】:

  • if(pszSearchWord == "") strcmp()。
  • szTemp1[10] 所以strcpy(szTemp1, "aabaaacaaaad"); 是个问题,因为您的字符串有超过 9 个字母
  • 谢谢大家,伙计们!我试试看!

标签: c


【解决方案1】:

替换

if(pszSearchWord == "")

通过

if (pszSearchWord[0] == 0)

pszSearchWord == "" 将地址 pszSearchWord 与字符串文字 "" 的地址进行比较,并且这些地址在您的情况下总是不同的。您不能使用 == 运算符比较字符串。

【讨论】:

    猜你喜欢
    • 2013-10-21
    • 2021-10-17
    • 2011-03-14
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多