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
//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;
}
Comments
Leave a comment