In this article, you will learn how to write a C program to search a substring in a given string.
Program to check if substring is present in the given string or not
Here we have a string represented by string array str[]
and a substring represented by substr[]
. Both of these strings are entered by the user. We are using while loop to search whether the entered substring is present in the given string or not.
If the substring is found, the flag variable is set to 1 else it is set to 0. At the end of the program, if the flag is 1, program prints a message “Substring is found in the entered string” else program prints this message “Substring is found in the entered string”.
#include<stdio.h> int main() { char str[80], substr[10]; int count1 = 0, count2 = 0, i, j, flag; //user enters the string printf("Enter a string: "); scanf("%s", str); //user enters the substring printf("Enter a substring to search: "); scanf("%s", substr); //'\0' represents the end of the string while (str[count1] != '\0') count1++; while (substr[count2] != '\0') count2++; for (i = 0; i <= count1 - count2; i++) { for (j = i; j < i + count2; j++) { flag = 1; if (str[j] != substr[j - i]) { flag = 0; break; } } if (flag == 1) break; } if (flag == 1) printf("Substring is found in the entered string"); else printf("Substring is not found in the entered string"); return 0; }
Output 1:
Output 2:
Output 3: As you can see this program is case sensitive, substring book is present in the given string, however due to the uppercase letter ‘B’ the program resulted in a “substring not found” response.
Leave a Reply