0

I have a problem with my C program. It's a command line argument of searching character string form the text file and output the line started with the user input character without using strstr(). It's OK but there is one problem. I want to output the whole file when Search Character is NULL. When I did this, the output become different of using strstr() build-in function. Can you help me what's wrong with my code, please?

#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;
}
Newbie
  • 23
  • 4
  • 5
    `if(pszSearchWord == "")` <== wrong way to compare strings. In C, use `strcmp()`. – pmg Apr 09 '14 at 11:43
  • `szTemp1[10]` so `strcpy(szTemp1, "aabaaacaaaad");` is a problem as your string has more than 9 letters – Dabo Apr 09 '14 at 11:45
  • 1
    Regarding string comparison, [one of the **many** duplicates on the subject](http://stackoverflow.com/questions/2603039/warning-comparison-with-string-literals-results-in-unspecified-behaviour). – WhozCraig Apr 09 '14 at 11:47

1 Answers1

2

Replace

if(pszSearchWord == "")

by

if (pszSearchWord[0] == 0)

pszSearchWord == "" compares the address pszSearchWord to the address of the string literal "" and those addresses are always different in your case. You cannot compare strings using the == operator.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115