Break string with multiple symbols

2

I have a string in the following format:

  

0: name: password: email: etc

I need to separate it in each ':', and I'm doing this with the strtok function (string, ':').

The problem is that the password can be null, and the default looks like this:

  

0: name :: email: etc

And then the strtok does not work anymore, because it does not only take the first ':', but both.

Is there any way to get around this by using strtok, or even make this process smarter?

Thank you.

    
asked by anonymous 06.12.2017 / 13:36

1 answer

2

Unfortunately, the strtok() function is not able to interpret two tokens as a "null" field.

One solution would be to implement another version of strtok() that is able to behave exactly the same but able to interpret tokens followed.

A solution based on the strpbrk() function follows:

#include <string.h>

char * strtok2( char * str, char const * delim )
{
    static char * src = NULL;
    char * p = NULL;
    char * ret = NULL;

    if(str)
        src = str;

    if(!src)
        return NULL;

    p = strpbrk( src, delim );

    if(p)
    {
        *p = 0;
        ret = src;
        src = ++p;
    }
    else if(*src)
    {
        ret = src;
        src = NULL;
    }

    return ret;
}

Testing:

int main( void )
{
    int i = 0;
    char str[] = "0:nome::email:etc";

    char * p = strtok2( str, ":" );

    while(p)
    {
        printf ("%d: %s\n", ++i, *p ? p : "[vazio]");

        p = strtok2( NULL, ":" );
    }

    return 0;
}

Output:

1: 0
2: nome
3: [vazio]
4: email
5: etc
    
06.12.2017 / 14:07