[英]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;
}
提前致謝
這是一個關於如何使用strsep
和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;
}
輸出:
<<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.