strsep() function was introduced as a replacement for strtok(3), since the latter cannot handle empty fields. However, strtok(3) conforms to C89/C99 and hence is more portable.
也就是说strsep是strtok的替代接口,但可能在移植的时候会出现问题。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char ptr[]={ "abc;defghijk; lmnopqrst ;uvwxyz "};
char *p = ptr, *str= "; ";
int i = 0;
char *sep = NULL;
printf("Original string : %s\n", ptr);
while((sep = strsep(&p, str)) != NULL)
{
if(!strcmp(sep, ""))
{
printf("more than %s appear \n", sep);
continue;
}
printf("Line %d: %s\n", ++i, sep);
}
return 0;
}
输出结果:
TestServer $ ./strsep
Original string : abc;defghijk; lmnopqrst ;uvwxyz
Line 1: abc
Line 2: defghijk
more than appear
more than appear
more than appear
more than appear
more than appear
Line 3: lmnopqrst
more than appear
Line 4: uvwxyz
more than appear
会多次出现空字符串的问题,这是因为strsep在处理多余一个的delimit字符是会返回空字符串代替NULL。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char ptr[]={ "abc;defghijk; lmnopqrst ;uvwxyz "};
char *p = ptr, *dlm= "; ";
int i = 0;
char *sep = NULL, *saveptr = NULL;
printf("Original string : %s\n", ptr);
while((sep = strtok_r(p, dlm, &saveptr)) != NULL)
{
printf("Line %d: %s\n", ++i, sep);
// note: p have to set NULL, or will not break while();
p = NULL;
}
return 0;
}
输出结果:TestServer$ ./strtok_r Original string : abc;defghijk; lmnopqrst ;uvwxyz
Line 1: abc
Line 2: defghijk
Line 3: lmnopqrst
Line 4: uvwxyzstrtok
函数会将多余一个delimit字符转换成'\0', 注意p = NULL操作,在第二次调用strtok&strtok_r时需要将str=NULL。