c函數: strtok 和 strtok_r 詳解

來源:互聯網
上載者:User

函數名:   strtok    
  功     能:   尋找由在第二個串中指定的分界符分隔開的單詞    
  用     法:   char   *strtok(char   *str1,   char   *str2);    
  程式例:    
   
  #include   <string.h>    
  #include   <stdio.h>    
   
  int   main(void)    
  {    
        char   input[16]   =   "abc,d";    
        char   *p;    
   
        /*   strtok   places   a   NULL   terminator    
        in   front   of   the   token,   if   found   */    
        p   =   strtok(input,   ",");    
        if   (p)       printf("%s\n",   p);    
   
        /*   A   second   call   to   strtok   using   a   NULL    
        as   the   first   parameter   returns   a   pointer    
        to   the   character   following   the   token     */    
        p   =   strtok(NULL,   ",");    
        if   (p)       printf("%s\n",   p);    
        return   0;    
  }   

 

帶有_r的函數主要來自於UNIX下面。所有的帶有_r和不帶_r的函數的區別的是:帶_r的函數是安全執行緒的,r的意思是reentrant,可重新進入的。

上述程式啟動並執行結果是
abc
d

 

 

1. strtok介紹
眾所周知,strtok可以根據使用者所提供的分割符(同時分隔字元也可以為複數比如“,。”)
將一段字串分割直到遇到"\0".

比如,分隔字元=“,” 字串=“Fred,John,Ann”
通過strtok 就可以把3個字串 “Fred”     “John”      “Ann”提取出來。
上面的C代碼為

 

QUOTE:int in=0;
char buffer[]="Fred,John,Ann"
char *p[3];
char *buff = buffer;
while((p[in]=strtok(buf,","))!=NULL) {
                 i++;
                 buf=NULL; }

如上代碼,第一次執行strtok需要以目標字串的地址為第一參數(buf=buffer),之後strtok需要以NULL為第一參數(buf=NULL)。指標列p[],則儲存了分割後的結果,p[0]="John",p[1]="John",p[2]="Ann",而buf就變成    Fred\0John\0Ann\0。

 

2. strtok的弱點
讓我們更改一下我們的計劃:我們有一段字串 "Fred male 25,John male 62,Anna female 16" 我們希望把這個字串整理輸入到一個struct,

 

QUOTE:struct person {
     char [25] name ;
     char [6] sex;
     char [4] age;
}

要做到這個,其中一個方法就是先提取一段被“,”分割的字串,然後再將其以“ ”(空格)分割。
比如: 截取 "Fred male 25" 然後分割成 "Fred" "male" "25"
以下我寫了個小程式去表現這個過程:

 

 

QUOTE:#include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
int main()
{
   int in=0;
   char buffer[INFO_MAX_SZ]="Fred male 25,John male 62,Anna female 16";
   char *p[20];
   char *buf=buffer;

 

   while((p[in]=strtok(buf,","))!=NULL) {
             buf=p[in];
             while((p[in]=strtok(buf," "))!=NULL) {
                       in++;
                       buf=NULL;
                    }
                 p[in++]="***"; //表現分割
                 buf=NULL; }

   printf("Here we have %d strings\n",i);
   for (int j=0; j<in; j++)
         printf(">%s<\n",p[j]);
   return 0;
}

這個程式輸出為:
Here we have 4 strings
>Fred<
>male<
>25<
>***<
這隻是一小段的資料,並不是我們需要的。但這是為什麼呢? 這是因為strtok使用一個static(靜態)指標來操作資料,讓我來分析一下以上代碼的運行過程:

 

紅色為strtok的內建指標指向的位置,藍色為strtok對字串的修改

1. "Fred male 25,John male 62,Anna female 16" //外迴圈

2. "Fred male 25\0John male 62,Anna female 16" //進入內迴圈

3.    "Fred\0male 25\0John male 62,Anna female 16"

4.    "Fred\0male\025\0John male 62,Anna female 16"

5 "Fred\0male\025\0John male 62,Anna female 16" //內迴圈遇到"\0"回到外迴圈

6   "Fred\0male\025\0John male 62,Anna female 16" //外迴圈遇到"\0"運行結束。

3. 使用strtok_r
在這種情況我們應該使用strtok_r, strtok reentrant.
char *strtok_r(char *s, const char *delim, char **ptrptr);

相對strtok我們需要為strtok提供一個指標來操作,而不是像strtok使用配套的指標。
代碼:

 

QUOTE:#include<stdio.h>
#include<string.h>
#define INFO_MAX_SZ 255
int main()
{
   int in=0;
   char buffer[INFO_MAX_SZ]="Fred male 25,John male 62,Anna female 16";
   char *p[20];
   char *buf=buffer;

 

   char *outer_ptr=NULL;
   char *inner_ptr=NULL;

   while((p[in]=strtok_r(buf,",",&outer_ptr))!=NULL) {
             buf=p[in];
             while((p[in]=strtok_r(buf," ",&inner_ptr))!=NULL) {
                       in++;
                       buf=NULL;
                    }
                 p[in++]="***";
                 buf=NULL; }

   printf("Here we have %d strings\n",i);
   for (int j=0; jn<i; j++)
         printf(">%s<\n",p[j]);
   return 0;
}

這一次的輸出為:
Here we have 12 strings
>Fred<
>male<
>25<
>***<
>John<
>male<
>62<
>***<
>Anna<
>female<
>16<
>***<

 

讓我來分析一下以上代碼的運行過程:

紅色為strtok_r的outer_ptr指向的位置,
紫色為strtok_r的inner_ptr指向的位置,
藍色為strtok對字串的修改

1. "Fred male 25,John male 62,Anna female 16" //外迴圈

2. "Fred male 25\0John male 62,Anna female 16"//進入內迴圈

3.   "Fred\0male 25\0John male 62,Anna female 16"

4   "Fred\0male\025\0John male 62,Anna female 16"

5 "Fred\0male\025\0John male 62,Anna female 16" //內迴圈遇到"\0"回到外迴圈

6   "Fred\0male\025\0John male 62\0Anna female 16"//進入內迴圈

 

註:

屬轉載

文章轉載串連:http://blog.chinaunix.net/u2/66402/showart_1168731.html

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.