Jayesh Bhoi
Jayesh Bhoi

Reputation: 25885

issue to extract token from sub token using strtok() function in c

Have written following code in c

#include "stdio.h"
#include "string.h"

int main()
{
    char str[] = "gatway=10.253.1.0,netmask=255.255.0.0,subnet=10.253.0.0,dns=10.253.0.203";
    char name[100],value[100];
    char *token1,*token2;
    char *commasp = ", ";
    char *equ="=";

    token1 = strtok(str,commasp);

    while(token1 != NULL)
    {
        token2 = strtok(token1,equ);
        sprintf(name,"%s",token2);
        token2 = strtok(NULL,commasp);
        sprintf(value,"%s",token2);

        printf("Name:%s Value:%s\n",name,value);
        token1 = strtok(NULL,commasp);
    }
    return 0;
}

My problem is i got only one printf like Name:gatway Value:10.253.1.0. i know last strtok() in while loop followed by previous strok() which turns to null so token1 get null value and break the loop. Have think solution for it to not use strtok() in while loop for sub token (getting name and value) and use other method to extract name and value but it seems to lengthy code(using for or while loop for character match).So any one have batter solution to packup code in single loop.

Upvotes: 0

Views: 399

Answers (2)

cnicutar
cnicutar

Reputation: 182649

You could use strtok_r instead of strtok.

char *key_value;
char *key_value_s;

key_value = strtok_r(str, ",", &key_value_s);

while (key_value) {
    char *key, *value, *s;

    key = strtok_r(key_value, "=", &s);
    value = strtok_r(NULL, "=", &s);
    printf("%s equals %s\n", key, value);
    key_value = strtok_r(NULL, ",", &key_value_s);
}

gatway equals 10.253.1.0
netmask equals 255.255.0.0
subnet equals 10.253.0.0
dns equals 10.253.0.203

Frankly though I think it would be easier to just look for , and when you find one look for = backwards.

Upvotes: 2

perreal
perreal

Reputation: 97948

You can do this in two steps, first parse the main string:

#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "gatway=10.253.1.0,netmask=255.255.0.0,subnet=10.253.0.0,dns=10.253.0.203";
    char name[100],value[100];
    char *commasp = ", ";
    char *ptr[256], **t = ptr, *s = str;

    *t = strtok(str, commasp);
    while (*t) {
        t++;
        *t = strtok(0, commasp);
    }

    for (t = ptr; *t; t++) { 
        printf("%s\n", *t); 
        // now do strtok for '=' ...
    }

    return 0;
}

Then parse individual pairs as before.

The above results in:

gatway=10.253.1.0
netmask=255.255.0.0
subnet=10.253.0.0
dns=10.253.0.203

Upvotes: 1

Related Questions