Sunday 13 January 2013

Remove all occurrences of a string from another string.


/*
Pattern:google
Input : I googled on google about google
Output: I d on  about
*/
#include<iostream.h>
#include<conio.h>
#include<string.h>

using namespace std;

int main()
{
    string masterString ="I googled on google about google.";
    string pattern="google";
    int count =0;
    int masterLen = masterString.length();
    int patternLen = pattern.length();
    for(int i =0 ; i<= masterLen ; i++)
    {
        if(masterString.substr(i,patternLen) == pattern)
        {
            count++;
            i = i+patternLen;
        }
        if(count>0)
        {
            if(i < masterLen)
                masterString[i-count*patternLen] = masterString[i];
        }
    }
    cout<<masterString.substr(0,masterLen-count*patternLen);
    getch();
}

No comments:

Post a Comment