Split string with delimiters in C

前端 未结 20 1414
你的背包
你的背包 2020-11-21 11:56

How do I write a function to split and return an array for a string with delimiters in the C programming language?

char* str = \"JAN,FEB,MAR,APR,MAY,JUN,JUL,         


        
20条回答
  •  忘了有多久
    2020-11-21 12:11

    Below is my strtok() implementation from zString library. zstring_strtok() differs from standard library's strtok() in the way it treats consecutive delimiters.

    Just have a look at the code below,sure that you will get an idea about how it works (I tried to use as many comments as I could)

    char *zstring_strtok(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

    Below is an example usage...

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

    The library can be downloaded from Github https://github.com/fnoyanisi/zString

提交回复
热议问题