Check if String contains Substring in C Language
To check if a string contains given substring, iterate over the indices of this string and check if there is match with the substring from this index of the string in each iteration. If there is a match, then the substring is present in this string.
C Program
In the following program, we take a string in str
and substring in substr
, take a for loop to iterate over the indices of string str
, check if substring substr
is present from this index of this string str
in each iteration.
Refer C For Loop tutorial.
main.c
#include <stdio.h>
#include <stdbool.h>
int main() {
char str[30] = "apple banana";
char substr[30] = "bana";
bool isPresent = false;
for (int i = 0; str[i] != '\0'; i++) {
isPresent = false;
for (int j = 0; substr[j] != '\0'; j++) {
if (str[i + j] != substr[j]) {
isPresent = false;
break;
}
isPresent = true;
}
if (isPresent) {
break;
}
}
if (isPresent) {
printf("String contains substring.\n");
} else {
printf("String does not contain substring.\n");
}
return 0;
}
The outer For Loop is used to iterate over the indices of this string.
The inner For Loop is used if the substring matches with the string from this index. If substring matches, then substring is present and we may stop searching it next indices.
Output
String contains substring.
Program ended with exit code: 0
Conclusion
In this C Tutorial, we learned how to check if a string contains a given substring, with examples.