CodingHowTo

Find and Replace Substrings in C++ (No Regex Needed)

Find and Replace Substrings in C++ (No Regex Needed)

Content

When dealing with string manipulation, finding and replacing substrings is a common task. In C++, you can achieve this using the standard library's string functions in combination with loops or algorithms.

```cpp
#include <iostream>
#include <string>

std::string findAndReplace(const std::string& input, const std::string& toFind, const std::string& replaceWith) {
    std::string result = input;
    size_t pos = result.find(toFind);
    while (pos != std::string::npos) {
        result.replace(pos, toFind.length(), replaceWith);
        pos = result.find(toFind, pos + replaceWith.length());
    }
    return result;
}

int main() {
    std::string text = "Hello World! Hello Universe!";
    std::string oldSubstring = "Hello";
    std::string newSubstring = "Hi";

    std::string newText = findAndReplace(text, oldSubstring, newSubstring);
    std::cout << newText << std::endl; // Output: Hi World! Hi Universe!

    return 0;
}    

Conclusion

Using C++'s standard library, you can easily find and replace substrings without the need for regular expressions. This method is both simple and efficient, making it ideal for basic text manipulation tasks.