Tuesday 24 June 2014

C++ program to count number of times sub string appears in a string


Here is a C++ program to count number of times sub string appears in a string


 SOURCE CODE OUTPUT
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
    char str[300],subst[20];
    int i,j=0,nwrd=0;
    cout<<"Enter String : ";
    cin.getline(str,300);
    cout<<"Enter substring : ";
    cin>>subst;
    for(i=0;str[i]!='\0';i++)
    {
        if(str[i]==subst[j])
            j++;
        else if(str[i]!=subst[j])
            j=0;
        if(subst[j]=='\0')
        {
            nwrd++;
            j=0;
        }
    }
    cout<<"Number of times substring appears : "<<nwrd;
    return 0;
}

Any questions regarding to program please write in comments.

No comments:

Post a Comment