You're juggling with indexes, which is quite confusing. Use the indexes for one purpose only and don't set and reset at will. I would suggest to rewrite your function a bit and cleanup the used indexes
int strindex(char s[], char t[])
{
int foundIndex = -1;
int i,j;
for (i = 0; s[i]!='\0'; i++)
{
if(s[i]==t[0])
{
for(j = 1; s[i + j]!='\0' && t[j]!='\0' && s[i + j]==t[j]; j++)
;
if (t[j]=='\0') /**check if it null**/
{
printf("found match");
foundIndex = i;
}
}
}
return foundIndex;
}
You can replace the inner loop with strncmp
of course.
And now to your question ;-). Your strindex
works as intended. As @wildplasser already noted, fgets
stores the final newline \n
in the buffer. Since there's no newline in the string to be searched except at the end, you never get a match, if the string to search for is in the middle and not at the end.
When you either strip the newline from a[]
and b[]
, you will see, that strindex works.
Another approach could be to give the strings on the command line instead of reading with fgets.
int main(int argc, char **argv)
{
int search;
printf("\n\n THE FIRST STRING IS:%s\n\n THE SEARCH STRING IS:%s", argv[1], argv[2]);
printf("\n\n");
search = strindex(argv[1], argv[2]);
if(search==-1)
printf("The second String didnt found in the first string\n");
else printf("The second string appear in the first string at most right at index:%d\n",search);
return 0;
}