count the number of times the pattern string P occurs in the source string S
note that overlapping sequences are counted as separate occurrences.
Program
#include<stdio.h>
#include <string.h>
int main()
{
char s[8192];
char p[8192];
int ch;
printf("enter source string\n");
ch=getchar(); /* reading characters till getting new line */
int i=0;
while(ch!='\n')
{
s[i]=ch;
i++;
ch=getchar();
}
s[i]='\0'; /* placing null character at the end for ease of string operations */
printf("\nenter pattern string\n");
ch=getchar(); /* reading characters for pattern string till getting newline */
int j=0;
while(ch!='\n')
{
p[j]=ch;
j++;
ch=getchar();
}
p[j]='\0'; /* placing null character at the end for ease of string operations */
int lens,lenp;
lens= strlen(s);
lenp= strlen(p);
int count=0;
int a;
for(i=0;i<=(lens-lenp);i++)
{
a=1;
for(j=0;j<(lenp);j++)
{
if(s[i+j]!=p[j])
{
a=0;
j=lenp;
}
}
if(a==1)
count++;
}
printf("%d",count);
return 0;
}
Sample input and output:
enter source string
gotohome goto sleep
enter pattern string
goto
2