Question

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" ...

Was it helpful?

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.

OTHER TIPS

There is no need to use iterators. You can use member function find of class std::string

For example

#include <iostream>
#include <string>

int main();
{
    std::string s("foo $deli: baa $deli: don't $deli: matter");
    std::string deli("$deli:");

    typedef std::string::size_type size_type;

    for ( size_type i = 0; ( i = s.find( deli, i ) ) != std::string::npos; i += deli.size() )
    {
        std::cout << s.substr( i + deli.size() ) << std::endl;
    }

    std::cout << std::endl;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top