Sunday, 31 October 2010

C Program To Count the Occurence of a Substring in String

/* 
  * C Program To Count the Occurence of a Substring in String 
  */
 #include <stdio.h>
 #include <string.h>
  
 Char s[100], sub[100];
 int cnt =0, cnt1 =0;
  
 void main()
 {
   inti, j, l, l1, l2;
  
 printf("\nEnter a string : ");
 scanf("%[^\n]s",s);
  
     l1 =strlen(s);
  
 printf("\nEnter a substring : ");
 scanf(" %[^\n]s", sub);
  
     l2 =strlen(sub);
  
 for(i=0;i< l1;)
 {
         j =0;
         cnt =0;
 while((s[i]== sub[j]))
 {
             cnt++;
 i++;
             j++;
 }
 if(cnt == l2)
 {
             cnt1++;
             cnt =0;
 }
 else
 i++;
 }
 printf("%s occurs %d times in %s", sub, cnt1,s);
 }

No comments:

Post a Comment