Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

find and replace string 1 with string 2: Part 1. Writ a function with header rep

ID: 3553769 • Letter: F

Question

find and replace string 1 with string 2:


Part 1. Writ a function with header replace_string(strings str, string str0, string str1) All the sub string str0 in string str should be replaced by sub string strl. This function is given in the file: replacing string.cpp Hints: 1) You may need to use the find(), erase() and insert() member functions of C++ string. Note that the member function str. find(s2,0) returns the largest unsigned in t value if string s2 does not exist in the string str. Note that if you use an int type variable to store the value of str. find(s2,0), there is overflow when s2 does not exist in str. You need to consider that there may be more than one strO in str. Write a program to read the file C:mycomputerstrings.txt you need to save it into the directory C:mycomputer . Replace all the substring "ung" with "on" (you need to call the function replace string ), then write the modified document into the text file lab9task2 corrected.txt. For example, the word "Natiungal" is changed to "National".

Explanation / Answer

void replace_string(string &str,string from,string to) {

if(from.empty())

return;

size_t start_pos = 0;

while((start_pos = str.find(from, start_pos)) != std::string::npos) {

str.replace(start_pos, from.length(), to);

start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'

}

}


Now whole Code :

#include <iostream>

#include <fstream>

using namespace std;

void replace_string(string &str,string from,string to) {

if(from.empty())

return;

size_t start_pos = 0;

while((start_pos = str.find(from, start_pos)) != std::string::npos) {

str.replace(start_pos, from.length(), to);

start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'

}

}

int main() {

ifstream fin;

fin.open("C:mycomputersStrings.txt");

ofstream fout;

fout.open("lab9task2_corrected.txt");

string s;

while(fin) {

fin>>s;

replace_string(s,"ung","on");

fout<<s<<endl;

}

return 0;

}