strtok_r函数研究

strtok_r函数研究

  (2009-07-10 14:10:55)
标签: 

杂谈

分类: MSN搬家
strtok/strtok_r函数用于分割字符串,区别在于前者线程不安全,后者是线程安全的。
函数原型:
             #include <string.h>
 
             char *strtok(char *s, const char *delim);
 
             char *strtok_r(char *s, const char *delim, char **ptrptr);

这两个函数会修改被搜索的字符串,linux手册是不推荐使用的。

例如字符串为:
123oo456oo789oo
strtok_r函数依次返回字符1所在的位置,修改第一个'o'为'\0'
返回4所在的位置,修改第三个'o'为'\0',
...

测试程序如下:



#include<stdio.h>
#include<string.h>

int main()
{
       char * str;
       str = (char *)malloc(20);
       bzero(str,20);
       sprintf( str, "123%s456%s789%s","oo","oo","oo");
       printf("%s length=%d\n",str,strlen(str));
       int length = strlen(str);     

       char * tok=NULL;
       char *myStrBuf=NULL;
   int       idx = 0;
       printf("%d   while...\n",(int)(str));
       while (1) {
              //tok = strtok_r(str,"o",ptrptr);
              if (!idx)
                     tok = strtok_r(str,"oo",&myStrBuf);
              else
                     tok = strtok_r(NULL,"oo",&myStrBuf);
            
              printf("\n\nidx = %d\n",idx);
              if (tok) {
                     printf( "%s length = %d %d\n\n",tok,strlen(tok),(int)(tok));
                     idx++;
              }
              else{
                     printf("NULL\n\n");
                     break;
                     //exit(0);
              }
       }
       printf("%s\n",str);
       int i =0;
       for(;i<length;i++){     
              printf("%d ",(int)(str[i]));
       }
       printf("\n");
       if (myStrBuf){
              printf("%d\n",(int)(myStrBuf));
               //不要free myStrBuf
       }
}

123oo456oo789oo length=15
141664264   while...

idx = 0
123 length = 3 141664264
 
idx = 1
456 length = 3 141664269
 
idx = 2
789 length = 3 141664274
 
idx = 3
NULL
123
49 50 51 0 111 52 53 54 0 111 55 56 57 0 111
141664279

注意不要Free myStrBuf
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值