Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - split a string with pipes using strtok

Tags:

c

strtok

I have a string "1|4|1577|1|10.22.33|7001390280000019|||||172.20.5.20|1" and I want to split this string to get a result like this:

1
4
1577
10.22.33
7001390280000019
null
null
null
null
172.20.5.20
1

But when I use strtok in a while cycle, the pipes that doesn't have any content are not showing, so my result looks like this:

1
4
1577
1
10.22.33
7001390280000019
172.20.5.20
1

How can I get this result?

Here is my code:

int main(argc,argv)
int argc;
char *argv[];
{
    char *var1="1|4|1577|1|10.22.33|7001390280000019|||||172.20.5.20|1";
    char *var2=malloc(strlen(var1)+1);
    strcpy(var2,var1);
    while ((var2 = strtok(var2, "|")) != NULL){
        printf("<<%s>>\n", var2);
        var2= NULL;
    }
    return 0;
}

Thanks in advance

like image 900
Alan Gaytan Avatar asked Jun 10 '26 23:06

Alan Gaytan


1 Answers

Here's an example on how this would work with strsep and strdup:

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

int main()
{
    char *var1="1|4|1577|1|10.22.33|7001390280000019|||||172.20.5.20|1";
    char *p, *var2, *var3;
    var2=strdup(var1);   // allocates enough space for var1 and copies the contents
    var3=var2;           // save off var2, since strsep changes it
    while ((p = strsep(&var2,"|")) != NULL) {   // p contains the token
        printf("<<%s>>\n", p);
    }
    free(var3);          // var2 is now NULL, so use var3 instead
    return 0;
}

Output:

<<1>>
<<4>>
<<1577>>
<<1>>
<<10.22.33>>
<<7001390280000019>>
<<>>
<<>>
<<>>
<<>>
<<172.20.5.20>>
<<1>>
like image 109
dbush Avatar answered Jun 12 '26 11:06

dbush