Пошук та заміна тексту

C++:
Пошук та заміна тексту

How to: (Як робити:)

#include <iostream>
#include <string>
#include <algorithm>

int main() {
    std::string text = "Hello, World! Let's replace 'World' with 'Ukraine'.";
    std::string from = "World";
    std::string to = "Ukraine";

    // Find starting point of the sequence you want to replace
    size_t start_pos = text.find(from);
    if(start_pos != std::string::npos) {
        // Replace it
        text.replace(start_pos, from.length(), to);
    }

    std::cout << text << std::endl; // Output: Hello, Ukraine! Let's replace 'Ukraine' with 'Ukraine'.
    return 0;
}

Deep Dive (Поглиблений аналіз):

Long before C++ got its library, devs would manually loop through strings for search-and-replace. Now, we have std::string::find and std::string::replace for a cleaner approach.

Alternatives like regular expressions (std::regex) exist but are heavier and slower for simple tasks. Still, they’re king for complex patterns.

On implementation: searching typically runs O(n) complexity, where n is string length. For replacing, another O(m) is added, with m being the replacement’s length. Efficient for short texts or infrequent changes but can bog down with large-scale edits. Libraries like Boost can offer performance enhancements.

See Also (Дивіться також):