C 语言中的 strtok 调用小技巧

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 char *my_strtok(char *buf, char *delims)
 5 {
 6     static int first = 1;
 7     if(first){ //
 8         first = 0; // 互斥操作,确保后面代码仅在本次调用执行
 9         return strtok(buf, delims);
10     } else {
11         return strtok(NULL, delims);
12     }
13 }
14 
15 int main(int argc, char *argv[])
16 {
17     char buf[] = "abc=2345&xyd=%bf&xx=34&dfd=0";
18 
19     char *p;
20     while(p = my_strtok(buf, "&"))
21         printf("%s\n",p);
22     return 0;
23 }

char *strtok(char *buf, const char *delims);

标准库提供的strtok 是“具有破会性”的操作(对buf有破坏性);

第一次调用 指定要分割的字符串地址buf;

第二次调用 的时候该buf要改为NULL;

我这个my_strtok可以吧第一次调用和第二次调用统一起来,无需第二次调用改buf 为NULL;

等等。。。。有个缺陷,一个程序里只能用mystrtok分割的一个字符串!!!

补救办法是:再增加一个静态字符指针,用来记录上一次调用和本次调用的地址值是否改

 1 #include <stdio.h>
 2 #include <string.h>
 3 
 4 char *my_strtok(char *buf, char *delims)
 5 {
 6     static int first = 1;
 7     static char *last;
 8    
10     if(last != NULL && last != buf) // 要分割的字符串若改变
11         first = 1;
12     last = buf;
13 
14     if(first){
15         first = 0; // 互斥操作,确保后面语句在以后的函数调用中仅执行一次
16         return strtok(buf, delims);
17     } else {
18         return strtok(NULL, delims);
19     }
20 
21 }
22 
23 int main(int argc, char *argv[])
24 {
25     char buf[] = "abc=2345&xyd=%bf&xx=34&dfd=0";
26     char buf2[] = "a=1,b=2,c=3";
27     char *p;
28     while(p = my_strtok(buf, "&"))
29         printf("%s\n",p);
30 
31     while(p = my_strtok(buf2, ","))
32         printf("%s\n", p);
33 
34     return 0;
35 }
原文地址:https://www.cnblogs.com/mathzzz/p/2645017.html