Search code examples
c++stringiterationdelimiter

C++ set iterator after the next delimiter recursiv?


Problem: it_begin iterator should be placed behind the next deli

I need a solution where "s" is not touched only it_begin steps though the String to the next

#include <iostream>
#include <string>
#include <vector>

using namespace std;

string s("foo $deli: baa $deli: don't $deli: matter")
string deli("$deli:");

string::const_iterator it_begin = s.begin();
string::const_iterator it_end   = s.end();

// calculate

// while(it_begin at the last deli )
{



  cout << string(it_begin, it_end) << endl;     
}

Output 1 " baa $deli: don't $deli: matter"

Output 2 " don't $deli: matter"

Output 3 " matter" ...


Solution

  • Something like this should work (untested):

    std::string::const_iterator it_begin = s.begin();
    std::string::const_iterator it_end = s.end();
    std::string del = "$deli";
    
    while ( (it_begin = std::search(it_begin, it_end, del.begin(), del.end()))
             != it_end ) {
        it_begin += del.size();
        std::cout << std::string( it_begin, it_end );
    }
    

    This calls std::search repeatedly until there's no delimiter left to be found in the string. Note the increment of the resulting iterator - this is to avoid infinite loop.

    EDIT: Tested live example.