C - 使用strtok用管道拆分字符串

时间:2015-10-26 17:23:22

标签: c strtok

我有一个字符串" 1 | 4 | 1577 | 1 | 10.22.33 | 7001390280000019 ||||| 172.20.5.20 | 1"我想拆分这个字符串来得到这样的结果:

1
4
1577
10.22.33
7001390280000019
null
null
null
null
172.20.5.20
1

但是当我在一段时间内使用strtok时,没有任何内容的管道没有显示,所以我的结果如下:

1
4
1577
1
10.22.33
7001390280000019
172.20.5.20
1

我怎样才能得到这个结果?

这是我的代码:

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

提前致谢

2 个答案:

答案 0 :(得分:1)

以下是一个关于如何使用strsepstrdup的示例:

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

输出:

<<1>>
<<4>>
<<1577>>
<<1>>
<<10.22.33>>
<<7001390280000019>>
<<>>
<<>>
<<>>
<<>>
<<172.20.5.20>>
<<1>>

答案 1 :(得分:0)

感谢@BLUEPIXY和@dbush,代码完成如下:

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

char *strsep(char **sp, const char *sep);

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

char *strsep(char **sp, const char *sep){
    char *p, *s;
    if (sp == NULL || *sp == NULL || **sp == '\0') return(NULL);
    s = *sp;
    p = s + strcspn(s, sep);
    if (*p != '\0') *p++ = '\0';
    *sp = p;
    return(s);
}

结果:

<<1>>
<<4>>
<<1577>>
<<1>>
<<10.22.33>>
<<7001390280000019>>
<<>>
<<>>
<<>>
<<>>
<<172.20.5.20>>
<<1>>