facebook like button

25 August, 2011

A program to count the occurrences of a string in a given text

The need: 
     This is a simple program to count the occurrences of a string in a given text. The code is straight forward and uses built-in function strstr().
The code: 
---------------------------------------------------------

#include<stdio.h>
#include<string.h>

int count_occur(char *big, char *small);

int main()
{
    char big_string[]="The fat cat sat on a mat",search_string[]="at";
    printf("total %d occurrences found\n",count_occur(big_string,search_string));
    return 0;
}

int count_occur(char *big, char *small)
{
    char *temp;
    int count=0;
    temp=strstr(big,small);
    while (temp!=NULL)
    {
        temp=strstr(temp+1,small);
        count++;
    }
    return (count);
}
--------------------------------------------------------

No comments:

Post a Comment

feel free to ask your doubts... if any
you can post your doubts on
www.facebook.com/programsimply