Given a string and a sub-string, check if the sub-string exist in the main-string and display the count of the sub-string present in the string.
#include <stdio.h> #include<string.h> #include<stdlib.h> int main(void) { char *m,*s; int mlen,slen; int i,j,index,k,flag=1,fla=1,count=0; /* Allocate memory for the main string */ m=(char*)malloc(sizeof(char)); /* Allocate memory for the sub-string */ s=(char*)malloc(sizeof(char)); /* Get the main-string from the user */ scanf("%s",m); /* Get the sub-string from the user */ scanf("%s",s); /* Calculate the length of the main string */ mlen=strlen(m); /* Calculate the length of the sub-string */ slen=strlen(s); /* Open the main-string window */ for(i=0;i<mlen;i++) { flag=1; fla=1; /* If the first character of the sub-string matches with any of the character anywhere in the main string */ if(*(m+i)==*s) { /* Copy the index where the first character of the sub-string matches */ index=i; k=i; /* Open the window for the sub-string */ for(j=0;j<slen;j++) { /* If the characters matches, simply increment the j pointer and k pointer which moves pointers to next character of main string and sub-string */ if(*(m+k)==*(s+j)) k++; else { /* Else set the flag, so that atleast one character doesn't matches with main-string from the sub-string window */ flag=0; break; } } /* If the flag was not set, there exists at least one index where the sub-string matches with the main string */ if(flag) { /* Print the index of the sub-string match */ printf("found at index %d\n",index); /* Keep the count of the sub-string match occurence */ count++; fla=0; } } } /* If the sub-string have not occurred for at least one time, then print the sub-string is not found */ if(fla) printf("not found"); else /* Atlast print the count of the sub-string occurred in the main string. */ printf("\nIt has occured %d times",count); return 0; }