Search code examples
calgorithmbooleanc-stringsstrstr

Why does my program return true as the result is expected to be false?


I'm implementing the C "strstr" function in C. This function takes 2 string in parameter and tell whether or not, the 1st string contains the second one. However, while the result is expected to be false, it returns true. Could you give me an explanation, please ?

Here is code :

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

int searchStr(char *ch1, char *ch2);

int searchStr(char *ch1, char *ch2)
{
    int i = 0;
    int j = 0;
    while (i < strlen(ch1) - 1)
    {
        while (j < strlen(ch2) - 1)
        {
            if(i == strlen(ch1) - 1) 
            {
                return 0;
            }
            else
            {
              if (ch1[i] == ch2[j])
            {
                j++;
                i++;
            }
            else
            {
                if (j > 0)
                {
                    j = 0;
                }
                else
                {
                    i++;
                }
            } 
            }
        }
        return 1;
    }
}

int main()
{
    printf("%d", searchStr("science", "sh"));

} 

Regards

YT


Solution

  • It is because the function definition does not make a sense.:)

    For this while loop

    while (i < strlen(ch1) - 1)
    {
    

    this if statement in the inner while loop

            if(i == strlen(ch1) - 1) 
    

    always evaluates to logical false when strlen( ch2 ) is equal to 2.

    Thus this return statement

    return 0;
    

    never gets the control in this case.

    That is the inner while loop will have only one iteration and when the loop gets the control i is less than strlen(ch1) - 1 due to the condition of the outer while loop.