| 3 | #include <string> |
| 4 | |
| 5 | int main() |
| 6 | { |
| 7 | std::string text; // The string to be modified |
| 8 | std::cout << "Enter a string terminated by *:\n"; |
| 9 | std::getline(std::cin, text, '*'); |
| 10 | |
| 11 | std::string word; // The word to be replaced |
| 12 | std::cout << "Enter the word to be replaced: "; |
| 13 | std::cin >> word; |
| 14 | |
| 15 | std::string replacement; // The word to be substituted |
| 16 | std::cout << "Enter the string to be substituted for " << word << ": "; |
| 17 | std::cin >> replacement; |
| 18 | |
| 19 | if (word == replacement) // Verify there's something to do |
| 20 | { |
| 21 | std::cout << "The word and its replacement are the same.\n" |
| 22 | << "Operation aborted." << std::endl; |
| 23 | return 1; |
| 24 | } |
| 25 | |
| 26 | size_t start {text.find(word)}; // Index of 1st occurrence of word |
| 27 | while (start != std::string::npos) // Find and replace all occurrences |
| 28 | { |
| 29 | text.replace(start, word.length(), replacement); // Replace word |
| 30 | start = text.find(word, start + replacement.length()); |
| 31 | } |
| 32 | |
| 33 | std::cout << "\nThe string you entered is now:\n" << text << std::endl; |
| 34 | } |