#include <iostream> using namespace std; const int Msize = 500; void findAndReplace(char inputText[], const char targetWord[], const char replacementWord[]) { int position = 0; int targetLength = 0; int replacementLength = 0; while (inputText[position] != '\0') { position++; } while (targetWord[targetLength] != '\0') { targetLen++; } while (replacementWord[replacementLength] != '\0') { replacementLength++; } for (int i = 0; i < position; ++i) { bool found = true; for (int j = 0; j < targetLength; ++j) { if (inputText[i + j] != targetWord[j]) { found = false; break; } } if (found) { for (int j = 0; j < replacementLength; ++j) { inputText[i + j] = replacementWord[j]; } i += replacementLength - 1; } } } int main() { char text[Msize + 1]; char findWord[Msize]; char replaceWord[Msize]; // Input text cout << "Please enter the text (500 chars max):" << endl; cin.getline(text, Msize + 1); while (true) { // Input word to find cout << "Please enter the word to find (or enter an empty word to exit):" << endl; cin.getline(findWord, Msize); // Check for exit condition if (findWord[0] == '\0') { break; } // Input word to replace cout << "Please enter the replace word:" << endl; cin.getline(replaceWord, Msize); // Find and replace findAndReplace(text, findWord, replaceWord); // Display result cout << "Result:" << endl; cout << text << endl; } return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter