Break string with multiple symbols

Asked

Viewed 164 times

2

I have a string in the following format:

0:name:password:email:etc

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

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

0:name::email:etc

And then Strtok doesn’t work anymore, because it doesn’t just take the first ':', but both.

Is there any way around this using Strtok, or even doing this process in a smarter way?

Thank you.

  • What you want to appear if the password or any other option is null ?

  • Nothing, an empty string. The problem is that the function takes the email (in the example) and then messes up the rest of the code.

1 answer

2


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

One solution would be to implement another version of strtok() capable of behaving exactly the same, but capable of interpreting tokens in a row.

Follows a solution based on the function strpbrk():

#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;
}

Exit:

1: 0
2: nome
3: [vazio]
4: email
5: etc
  • Perfect! Thank you.

  • What is the need for this ? p = strtok2( NULL, ":" );

  • @YODA: Return the pointer to the die after the next token.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.