programming-examples/c/String/C Program To Count the Occurence of a Substring in String.c

50 lines
1.1 KiB
C
Raw Normal View History

2019-11-15 12:59:38 +01:00
/*
* C Program To Count the Occurence of a Substring in String
*/
#include <stdio.h>
#include <string.h>
char str[100], sub[100];
int count = 0, count1 = 0;
void main()
{
int i, j, l, l1, l2;
printf("
Enter a string : ");
scanf("%[^
]s", str);
l1 = strlen(str);
printf("
Enter a substring : ");
scanf(" %[^
]s", sub);
l2 = strlen(sub);
for (i = 0; i < l1;)
{
j = 0;
count = 0;
while ((str[i] == sub[j]))
{
count++;
i++;
j++;
}
if (count == l2)
{
count1++;
count = 0;
}
else
i++;
}
printf("%s occurs %d times in %s", sub, count1, str);
}
Enter a string :
prrrogram c prrrogramming
Enter a substring :
rr
rr occurs 2 times in prrrogram c prrrogramming