char * strtok_r(char *ptr, const char *sep, char **end)
{
if(!ptr)
/* we got NULL input so then we get our last position instead */
ptr = *end;
/* pass all letters that are including in the separator string */
while(*ptr && strchr(sep, *ptr))
++ptr;
if(*ptr)
{
/* so this is where the next piece of string starts */
char *start = ptr;
/* set the end pointer to the first byte after the start */
*end = start + 1;
/* scan through the string to find where it ends, it ends on a
null byte or a character that exists in the separator string */
while(**end && !strchr(sep, **end))
++*end;
if(**end)
{
/* the end is not a null byte */
**end = '\0'; /* zero terminate it! */
++*end; /* advance the last pointer to beyond the null byte */
}
return start; /* return the position where the string starts */
}
/* we ended up on a null byte, there are no more strings to find! */
return NULL;
}
----------------------------------------------------
使用方法
----------------------------------------------------
int main(int argv,char** argc)
{
char * str;
str = (char *)malloc(20);
memset(str,20,0);
sprintf( str, "123%s456%s789%s","oo","oo","oo");
int length = strlen(str);
char * tok=NULL;
char *myStrBuf=NULL;
int idx = 0;
while (1)
{
if (!idx)
tok = strtok_r(str,"oo",&myStrBuf);
else
tok = strtok_r(NULL,"oo",&myStrBuf);
if (tok)
{
printf("%s \n ",tok );
idx++;
}
else
{
printf("NULL\n\n");
break;
}
}
if (myStrBuf)
{
//printf("%d\n",(int)(myStrBuf));
free(str);
}
system("pause");
}
strtok_r 字符分割
最新推荐文章于 2023-04-24 14:24:51 发布