Search code examples
cstringsubstring

1 out of 7 test cases don't work with this simple C program to find sub-string


I've been given an assignment to write a C program to find a sub-string with 7 test cases. I've written the program but it only passes 6 test cases. 7th one fails and I'm unable to identify the reason behind it.

Edit: Here's the question that I was given for the assignment.

Write a program that takes two input strings S1 and S2 and finds if S2 is a substring of S1 or not. If S2 is a substring of S1, the program should print the index at S1 at which there is a match. If S2 is not a substring of S1, the program should print -1. If S2 appears in S1 multiple times, print the first index in S1 at which the match occurred.

Here's the source code of the program that I've written.

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

int main() {
    char st1[19];
    char st2[19];
    int cnt,i,k,c,len,m,sign;
    scanf("%s %s", st1, st2);
    len=strlen(st1);
    for(i=0; i<len; i++) {
        c=0;
        if (st1[i] == st2[c]) {
            m = i;
            sign = 0;
            cnt = 0;
            while(st2[c] != '\0' && sign!=1) {
                if (st1[m] == st2[c]) {
                    m++;
                    c++;
                    cnt++;
                } else
                    sign=1;
            }
            if (sign == 0) {
                printf("%d",i);
                k=1;
            }
        }
    }
    if (k != 1)
        if (sign!=0)
            printf("-1");
    return 0;
}

The 7th test case is as follows

Input:

coolgoose oo

Expected output:

1

Actual output:

15

Edit 2: And here are the other test cases that were passed.

Input       Output

football foot   0

mickey mouse    -1

abcdefghijklmnopqrs s   18

helloworld helloworld   0

FrodoBaggins bagg   -1

Hell Hello  -1

Solution

  • It's actually printing each match it finds: at character 1 and at character 5. You should break out of the for loop when you find a match.