Find all occurrences of a substring in a string
C program to find all occurrences of a substring in a given string.
Program
#include<stdio.h>
#include<conio.h>
#define MAX 50
void main()
{
char str[MAX], sub_str[MAX];
int i, j, flag;
printf("Enter the string\t:");
gets(str);
printf("Enter Substring to be searched\t:");
gets(sub_str);
i = 0;
while(str[i] != '\0')
{
if(str[i] == sub_str[0])
{
j = 0;
flag = 1;
while(sub_str[j] != '\0')
{
if(str[i+j] != sub_str[j])
{
flag = 0;
break;
}
j++;
}
if(flag == 1)
{
printf("\nSubstring '%s' found at position %d",sub_str,i+1);
}
}
i++;
}
if(flag == 0)
{
printf("\nSubstring not found");
}
getch();
}
Output
Enter the string :welcome to coursecrux.com
Enter Substring to be searched :co
Substring 'co' found at position 4
Substring 'co' found at position 12
Substring 'co' found at position 23