精品理论电影在线_日韩视频一区二区_一本色道精品久久一区二区三区_香蕉综合视频

c函數:strtok和strtok_r詳解

發布時間:2011-08-29 共2頁

  函數名:   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;

  }

百分百考試網 考試寶典

立即免費試用