Answer to Question #295555 in C++ for Paco

Question #295555

Write a program to:

  1. Store the following message into a string (DO include periods!):
  2. I am the door of the sheep. All who came before me are thieves and robbers, I am the door.
  3. Insert the following message after the comma in the string.
  4. but the sheep did not listen to them.
  5. Output the string to the screen with a new line at the end.
  6. Replace the following words in the string.
  7. a. “I” and "me" with “Jesus”
  8. b. “am” with “is”
  9. Note: Make sure you only replace the word “ am“ and not the letters “am" that might appear in that sequence in another word
  10. Output the string with a new line at the end.

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.
1
Expert's answer
2022-02-09T05:55:16-0500
#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;
}

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