strtok_r 字符分割

6 篇文章 0 订阅
3 篇文章 0 订阅


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");

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值