Replace a sub-string in a string in C++
Understanding String Manipulation
Replacing a sub-string in a string means finding a specific sequence of characters and replacing it with another sequence.
We will explore three different methods to achieve this in C++.
Method 1: Using Loop
This method iterates through the string and replaces occurrences of the sub-string.
#include <iostream> #include <algorithm> using namespace std; void replaceSubstring(string &str, const string &oldWord, const string &newWord) { size_t pos = 0; while ((pos = str.find(oldWord, pos)) != string::npos) { str.replace(pos, oldWord.length(), newWord); pos += newWord.length(); } } int main() { string str = "Hello World!"; replaceSubstring(str, "World", "C++"); cout << "Modified String: " << str; return 0; }
Output: Hello C++!
Method 2: Using Recursion
This method replaces the sub-string recursively.
#include <iostream> #include <algorithm> using namespace std; void replaceRecursive(string &str, const string &oldWord, const string &newWord) { size_t pos = str.find(oldWord); if (pos == string::npos) return; str.replace(pos, oldWord.length(), newWord); replaceRecursive(str, oldWord, newWord); } int main() { string str = "I love programming"; replaceRecursive(str, "love", "enjoy"); cout << "Modified String: " << str; return 0; }
Output: I enjoy programming
Method 3: Using String Functions
This method uses C++'s built-in find()
and replace()
functions.
#include <iostream> #include <algorithm> using namespace std; void replaceUsingFunctions(string &str, const string &oldWord, const string &newWord) { size_t pos = str.find(oldWord); if (pos != string::npos) { str.replace(pos, oldWord.length(), newWord); } } int main() { string str = "Replace old text"; replaceUsingFunctions(str, "old", "new"); cout << "Modified String: " << str; return 0; }
Output: Replace new text