Search code examples
c++splitstrtok

Searching for an alternative for strtok() in C++


I am using strtok to divide a string in several parts. In this example, all sections will be read from the string, which are bounded by a colon or a semicolon

char string[] = "Alice1:IscoolAlice2; Alert555678;Bob1:knowsBeepBob2;sees";
char delimiter[] = ":;";
char *p;

p = strtok(string, delimiter);

while(p != NULL) {
    cout << "Result: " << p << endl;

    p = strtok(NULL, delimiter);
}

As results I get:

Result: Alice1
Result: IscoolAlice2
Result:  Alert555678
Result: Bob1
Result: knowsBeepBob2
Result: sees

But I would like to get this results:

Result: Alice1:
Result: Alice2;
Result: Bob1:
Result: Bob2;

The restriction is that I can only choose individual characters when I use strtok. Does anyone know an alternative for strtok that I also can search for strings? Or has anyone an idea to solve my problem?


Solution

  • You can not do that task with strtok since you need more complex search

    Although I am not sure what is your string as delimiter but the same output can be done with:

    char string[] = "Alice1:IscoolAlice2; Alert555678;Bob1:knowsBeepBob2;sees";
    char delimiter[] = "(?:Alice|Bob)\\d.";
    std::regex regex( delimiter );
    std::regex_iterator< const char* > first( std::begin( string ), std::end( string ), regex  ), last;
    
    while( first != last ){
        std::cout << "Result: " << first->str() << '\n';
        ++first;
    }  
    

    the output:

    Result: Alice1;
    Result: Alice2;
    Result: Bob1;
    Result: Bob2;