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:
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;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.