/* Homework 3 problem 2 * This program finds the first occurence of a substring in a user defined string * Reports the location (0 being the first position) and exits OR reports the absence */ #include int main( int argc, char** argv ) { // Define character arrays // 1024 is the maximum size of the string, it could have been chosen differently char S1[1024]; char S2[1024]; // Promt user printf("Please enter the original string\n"); fgets(S1,1024,stdin); printf("Please enter the sub-string to be searched\n"); fgets(S2,1024,stdin); // During your testing it is always good to know what is the received from user //printf("Original string entered: %s",S1); //printf("Substring entered: %s",S2); int i,j=0,location=0; for(i=0;S1[i]!='\n';i++){ // if statement is true if there is a match if(S1[i]==S2[j]){ // Remember this location if j is zero, it is the initial character of substring if(j==0){ location = i; } // Advance to the next character on the substring j++; // If the termination character ('\n') on substring is reached // Print location and exit if(S2[j]=='\n'){ printf("Substring is found at location %d\n",location); exit(0); } } else{ // No match between current position of substring and current position of original string // Return to the first character of substring to compare for next iterations j=0; } } // If this line is reached, the program did not exit which so the substring is not found printf("Substring is NOT found\n"); exit(0); }