C版本自带的strtok函数的作用是对字符串按照分隔符进行分割,然后把每个字符串都显示出来。
但是这里有一个问题,比如:
a||b|c:如果使用C自带的处理的话,直接返回的就是a, b, c;但是我的需求中,需要把中间的空的字符也要取出来,也就是说,’a||b’,在两个分隔符中间没有字母,但是要提示我,而不是直接跳过了。
所以按照我的需求,将strtok进行了修改:
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
char * sttok_byqiu(char*s, const char* delim, int *flag)
{
int first_point = 0;
int secon_point = 0;
char *token = NULL;
static char* olds;
int t;
//s为空的情况下,说明是继续上面使用
if(s==NULL && olds != NULL)
{
s = olds;
}
else if( s != NULL )
olds = s;
else
{
*flag = -1;
return NULL;
}
//如果当前的s的第一个字符就是分隔符,说明第一个字符就是空
// ‘||||b’
if( *s == *delim )
{
*s = '\0';
token = NULL;
olds++;
*flag = 1;
return token;
}
token = s;
//查找第一个分隔符
s = strpbrk(token,delim);
//说明是没有分隔符结尾
if( s == NULL )
olds = NULL;//__rawmemchr(token, '\0');
else
{
*s = '\0';
olds = s+1;
}
*flag = 1;
return token;
}
int main()
{
char str[] = "1|2|3|||||7";
char *result = NULL;
int flag = 0;
result = sttok_byqiu(str, "|", &flag);
while( flag == 1 )
{
if( result != NULL )
{
if( *result != '\0' )
printf("result = %s\n", result);
else
printf("there is null\n");
printf("--------------------\n");
}
else
{
printf("there is null\n");
printf("--------------------\n");
}
result = sttok_byqiu(NULL, "|", &flag);
}
return 0;
}