// This program takes in a string, and a substring and then // searches the main string for the occurence of the substring // Week 4 Lecture 8 #include #include // Define the size of the array = this is clearly going to cause some // waste - one of the downfalls of arrays #define MAX_LENGTH 124 int main(void) { // Declare our array to hold the string char string[MAX_LENGTH]; char substring[MAX_LENGTH]; printf("Type in a string: "); // Read in the string using fgets() function fgets(string, MAX_LENGTH, stdin); printf("Type in a substring: "); // Read in the string using fgets() function fgets(substring, MAX_LENGTH, stdin); // Do some magic here to search: // How do we search through the main word? Do we do it all at // once or does it have to be character by character? // What would be the logic here? int main_len = strlen(string); int substring_len = strlen(substring); int flag = 1; // Check if the substring exists in the main string for (int i = 0; i <= main_len - substring_len; i++) { for (int j = i; j < i + substring_len; j++) { // Initialize the flag for matching substring flag = 1; if (string[j] != substring[j - i]) { flag = 0; // Set the flag to zero if characters don't match } } } if (flag == 1) { printf("The substring exists in the string.\n\n"); // Display message if the substring is found } else { printf("The substring does not exist in the string.\n\n"); // Display message if the substring is not found return 0; // Return 0 to indicate successful execution of the program } return 0; }