Write a program to:
The final output should be as follows:
Jesus is the door of the sheep. All who came before Jesus are thieves and robbers, but the sheep did not listen to them. Jesus is the door.
#include <iostream>
#include <string>
using namespace std;
void replace(string& s, const string& old_word, const string& new_word) {
size_t len_old = old_word.length();
size_t len_new = new_word.length();
size_t len_s = s.length();
size_t pos=0;
while (true) {
pos = s.find(old_word, pos);
if (pos == string::npos) {
break;
}
if ( (pos == 0 || s[pos-1] == ' ') &&
(pos + len_old == len_s || s[pos+len_old] == ' ' ||
s[pos+len_old] == ',' || s[pos+len_old] == '.') ) {
s.replace(pos, len_old, new_word);
pos += len_new;
len_s += len_new - len_old;
}
else {
pos += len_old;
}
}
}
int main() {
string message = "I am the door of the sheep. All who came before me are thieves and robbers, I am the door.";
size_t pos = message.find(',');
message.insert(pos, " but the sheep did not listen to them.");
cout << message << endl;
replace(message, "I", "Jesus");
replace(message, "me", "Jesus");
replace(message, "am", "is");
cout << message << endl;
return 0;
}
Comments
Leave a comment