How does strtok() split the string into tokens in C?

前端 未结 15 2031
陌清茗
陌清茗 2020-11-22 14:48

Please explain to me the working of strtok() function. The manual says it breaks the string into tokens. I am unable to understand from the manual what it actua

15条回答
  •  悲&欢浪女
    2020-11-22 15:43

    To understand how strtok() works, one first need to know what a static variable is. This link explains it quite well....

    The key to the operation of strtok() is preserving the location of the last seperator between seccessive calls (that's why strtok() continues to parse the very original string that is passed to it when it is invoked with a null pointer in successive calls)..

    Have a look at my own strtok() implementation, called zStrtok(), which has a sligtly different functionality than the one provided by strtok()

    char *zStrtok(char *str, const char *delim) {
        static char *static_str=0;      /* var to store last address */
        int index=0, strlength=0;           /* integers for indexes */
        int found = 0;                  /* check if delim is found */
    
        /* delimiter cannot be NULL
        * if no more char left, return NULL as well
        */
        if (delim==0 || (str == 0 && static_str == 0))
            return 0;
    
        if (str == 0)
            str = static_str;
    
        /* get length of string */
        while(str[strlength])
            strlength++;
    
        /* find the first occurance of delim */
        for (index=0;index

    And here is an example usage

      Example Usage
          char str[] = "A,B,,,C";
          printf("1 %s\n",zStrtok(s,","));
          printf("2 %s\n",zStrtok(NULL,","));
          printf("3 %s\n",zStrtok(NULL,","));
          printf("4 %s\n",zStrtok(NULL,","));
          printf("5 %s\n",zStrtok(NULL,","));
          printf("6 %s\n",zStrtok(NULL,","));
    
      Example Output
          1 A
          2 B
          3 ,
          4 ,
          5 C
          6 (null)
    

    The code is from a string processing library I maintain on Github, called zString. Have a look at the code, or even contribute :) https://github.com/fnoyanisi/zString

提交回复
热议问题