Home »
C programs »
C Strings User-defined Functions Programs
C program to check whether a substring is present in a given string
Problem statement
In this program, we will learn how to check whether a substring is present in a string or not without using library function?
We are implementing a function named myStrStr() this function will return 1 if substring present in the string and return 0, if substring is not present in the string.
Program to check substring in a string in C
#include <stdio.h>
#include <string.h>
//function declaration
int myStrStr(char* str, char* sub);
int main()
{
char str[100] = { 0 };
char strTocheck[10] = { 0 };
printf("Enter complete string: ");
scanf("%[^\n]s", str);
getchar();
printf("Enter string to check: ");
scanf("%[^\n]s", strTocheck);
if (myStrStr(str, strTocheck))
printf("String \"%s\" found in \"%s\"\n", strTocheck, str);
else
printf("String \"%s\" not found in \"%s\"\n", strTocheck, str);
return 0;
}
//function definition
int myStrStr(char* str, char* sub)
{
int flag = 0;
int i = 0, len1 = 0, len2 = 0;
len1 = strlen(str);
len2 = strlen(sub);
while (str[i] != '\0') {
if (str[i] == sub[0]) {
if ((i + len2) > len1)
break;
if (strncmp(str + i, sub, len2) == 0) {
flag = 1;
break;
}
}
i++;
}
return flag;
}
Output
First run:
Enter complete string: Hello how are you?
Enter string to check: how
String "how" found in "Hello how are you?"
Second run:
Enter complete string: Hello how are you?
Enter string to check: we
String "we" not found in "Hello how are you?"
Third run:
Enter complete string: Hello how are you?
Enter string to check: how are you?
String "how are you?" found in "Hello how are you?"
C Strings User-defined Functions Programs »