繁体   English   中英

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

[英]C - split a string with pipes using 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;
}

提前致谢

这是一个关于如何使用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>>

感谢@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>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM