Decode School

Decode School - The School for Problem Solvers

Welcome to my blog. Subscribe and get my latest blog post in your inbox.

Count the occurences of given substring in a String

Get a String and Substring and count the occurrence of substring in string.

Sample Input 1:

entertainment en

Sample Output 1:

2

Program or Solution

					    
							
#include<stdio.h>
#include<string.h>
int main()
{
	char str[50],s[30];
	int i,j,k,b,count=0;
	fgets(str,50,stdin);
	fgets(s,30,stdin);
	
	for(i=0;i<=strlen(str)-strlen(s);i++)
	{
		j=0;
		b=0;

		if(str[i]==s[j])
		{
			for(k=i;j<=strlen(s)-1;k++,j++)
			{
				if(str[k]!=s[j])
				{	
					b=1;	
					break;
				}
			}
			if(b==0)
			{
				count=count+1;
				
			}
		}
	}
	printf("%d",count);
	return 0;
}

	

					    
					

Program Explanation

check whether first character of sub string is equal to any character in string.

If it is equal, then check remaining characters are equal to the characters in substring.

else move to next character.