Q:

How to delete all occurrences of a specific string a string?

How to delete all occurrences of FOO in a string s = FOOTHEFOOFOOBEST for example so the output would be THE BEST without any extra spaces unlike my code does. 
Here is an sample of my try: 
#include <iostream>
#include <string>
int main() {

    std::string s = "FOOTHEFOOFOOBEST";
        for (int i = 0; i < s.size(); i++){
            if (s[i] == 'F'&&s[i + 1] == 'O' && s[i + 2] == 'O'){
                std::cout << ' ';
                i += 2;
            }
            else
                std::cout << s[i];
        }

        return 0;
}

The output of my code is THE  BEST there's an extra space however I expected THE BEST, Is there a simpler way to do that?

A:

I think I'd do it something like this:
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>

template<class Haystack, class Needle, class OutputIterator>
void separate(Haystack&& haystack, Needle&& needle, OutputIterator output_iter)
{
    const char* sep = "";

    auto first = std::begin(haystack);
    auto last = std::end(haystack);

    auto first_needle = std::begin(needle);
    auto last_needle = std::end(needle);
    auto needle_length = std::distance(first_needle, last_needle);

    while (first != last)
    {
        auto next = std::search(first, last, first_needle, last_needle);

        if (next == first)
        {
            first = std::next(first, needle_length);
        }
        else
        {
            std::cout << sep;
            std::copy(first, next, output_iter);
            sep = " ";
            first = next;
        }
    }
}

int main()
{
    using namespace std::literals;

    const auto needle = "FOO"s;

    const auto haystack = "FOOTHEFOOFOOBEST"s;

    separate(haystack, needle, std::ostream_iterator<char>(std::cout, ""));

    return 0;
}

expected output:
THE BEST

