Answer to Question #332330 in C++ for Zee

Question #332330

Write a C++ program that finds and reverse all the occurrences of a substring, pat, in a string,


text. Show the output on console. The data is read from a user provided input file named as


“input.txt”.


Example:


text: abcduyeruyabcdmneaabcabcd


pat: abcd


text: dcbauyeruydcbamneaabcdcba

1
Expert's answer
2022-04-22T16:44:12-0400




//Please before running program prepare file input.txt and run
//There is sample input.txt on the screenshoot
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
#include <algorithm>
using namespace std;
//Implement function for search all position pattern in basic string
void calcAll(string& s, vector<int>& z)
{
    int len = s.size();
    z.resize(len);


    int l = 0, r = 0;
    for (int i = 1; i < len; ++i)
        if (z[i - l] + i <= r)
            z[i] = z[i - l];
        else
        {
            l = i;
            if (i > r) r = i;
            for (z[i] = r - i; r < len; ++r, ++z[i])
                if (s[r] != s[z[i]])
                    break;
            --r;
        }
}
void ReversePattern(string& pat, const string& filenam)
{
    //Open file and reading string all line
    ifstream inp(filenam);
    if (!inp)
    {
        cout << "Hm Soryy file does not exist!!! Repeat again\n";
        return;
    }
    string line;
    while (getline(inp, line))//read each line
    {
        vector<int>vind;
        string str = pat + line;
        calcAll(str, vind);
        for (int i = 0; i < str.size(); i++)
        {
                vind[i] -= pat.size();
        }
        int cnt = 0;
        string newLine="";
        for (int i = pat.size(); i < str.size(); i++)
        {
            if (vind[i] >= 0)
            {
                for (int j = pat.size() - 1; j >= 0; j--)
                    newLine += pat[j];
                cnt++;
                i += pat.size() - 1;
            }
            else
                newLine += str[i];
        }
        cout << newLine << endl;
    }
    inp.close();
}
int main()
{
    string pat = "";
    cout << "Please input pattern:";
    cin >> pat;
    ReversePattern(pat, "input.txt");
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS