zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    你读了该博客中哪些超链接?有何感想
    最理想的师生关系是健身教练和学员的关系,在这种师生关系中你期望获得来自老师的哪些帮助?
    1500802028 王莉娟
    解码方法
    N皇后问题
    两个链表的交叉
    全排列
    交叉字符串
    翻转链表
    爬楼梯
  • 原文地址:https://www.cnblogs.com/mathzzz/p/2645017.html
Copyright © 2011-2022 走看看