Hi i need help please,
the main program below uses a ”helper” function substr() to determine and report if the secondstring that the user enters is ”contained in” the first string. I need to use a nested for loop for this. So far, the program reports certain characters from the second string as false even if they are contained. I do not know what to add or modify to get the program to accurately report all given characters.
Code:
#include <stdio.h>
#include <string.h>
// returns the starting index of the first such occurrence
// where sub_str was found within str - if one exists
// otherwise returns -1
int substr(const char str[], const char sub_str[]);
int main()
{
char str[255];
printf("Enter a string: "); fflush(stdout);
scanf("%s", str);
char sub_str[255];
do
{
printf("Enter a string to search for (\"quit\" to quit): "); fflush(stdout);
scanf("%s", sub_str);
if ( strcmp(sub_str, "quit") )
{
int ind = substr(str, sub_str);
if ( ind == -1 )
{
printf("Not found: %s\n", sub_str);
}
else
{
printf("\"%s\" found at starting index %d\n", sub_str, ind);
}
}
} while ( strcmp(sub_str, "quit") );
printf("Done!\n");
return 0;
}
int substr(const char str[], const char sub_str[])
{
int i, j, big = strlen(str), small = strlen(sub_str), flag = 0;
for(i=0; i<(big-small); i++)
{
for(j=0; j<small; j++)
{
if(str[i+j]!=sub_str[j])
{
i+=1;
}
else
{
flag = 1;
}
}
if (flag)
return i;
else
{
i++;
}
}
return -1;
}