Chinaunix首页 | 论坛 | 博客
  • 博客访问: 450914
  • 博文数量: 80
  • 博客积分: 2301
  • 博客等级: 大尉
  • 技术积分: 884
  • 用 户 组: 普通用户
  • 注册时间: 2007-10-16 20:07
个人简介

I\'m interested in mathematics and Daoism. Welcome to talk about these subjects with me.

文章分类

全部博文(80)

文章存档

2017年(2)

2016年(16)

2015年(4)

2014年(6)

2013年(22)

2012年(2)

2011年(1)

2010年(4)

2009年(20)

2008年(2)

2007年(1)

我的朋友

分类: C/C++

2008-04-13 11:49:02

                       strtok_r函数研究
strtok/strtok_r函数用于分割字符串,区别在于前者线程不安全,后者是线程安全的。
函数原型:
       #include
 
       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',
...

测试程序如下:

/*
 * author: lujiandong
 * date:2008-4-13
 * description: test strtok_r
 */

#include
#include

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        printf("%d ",(int)(str[i]));
    }
    printf("\n");
    if (myStrBuf){
        printf("%d\n",(int)(myStrBuf));
        //不要free myStrBuf
    }
}

我在Red Hat Enterprise Linux AS release 4 (Nahant)下的输出信息:

157114376  while...
idx = 0
123 length = 3 157114376
 
idx = 1
456 length = 3 157114381
 
idx = 2
789 length = 3 157114386
 
idx = 3
NULL
 
123
49 50 51 0 111 52 53 54 0 111 55 56 57 0 111
157114390
注意不要Free获得的字符串


 
阅读(7856) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~