strtok_r函数研究

来源:互联网 发布:畅捷通是什么软件 编辑:程序博客网 时间:2024/06/06 04:28


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',
...

测试程序如下:

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

#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
    }
}

我在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获得的字符串

原创粉丝点击