C Program to Check if the Substring is Present in the Given String
Write a C program to check if the substring is present in the given string.
- Reads the main string and substring character-by-character until a newline (\n) is encountered.
- Loops through each character of the main string to check for a potential substring match starting at that index.
- Compares characters of the substring with the corresponding characters in the main string using nested while.
- If the entire substring matches, sets a found flag and breaks; prints the result based on this flag.
Example : pgm.c
#include <stdio.h> int main() { char str[100], substr[50]; int i = 0, j = 0, found = 0; printf("Enter the main string: "); while ((str[i] = getchar()) != '\n') { i++; } str[i] = '\0'; printf("Enter the substring: "); while ((substr[j] = getchar()) != '\n') { j++; } substr[j] = '\0'; // Check for substring match for (i = 0; str[i] != '\0'; i++) { int k = i, l = 0; while (str[k] == substr[l] && substr[l] != '\0') { k++; l++; } if (substr[l] == '\0') { found = 1; break; } } if (found){ printf("Substring found in the main string.\n"); }else{ printf("Substring not found in the main string.\n"); } return 0; }
Output :
Enter the main string: Welcome Ram
Enter the substring: Ram
Substring found in the main string.
Enter the substring: Ram
Substring found in the main string.