Split string with delimiters in C

前端 未结 20 1395
你的背包
你的背包 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:07

    My code (tested):

    #include 
    #include 
    #include 
    
    int dtmsplit(char *str, const char *delim, char ***array, int *length ) {
      int i=0;
      char *token;
      char **res = (char **) malloc(0 * sizeof(char *));
    
      /* get the first token */
       token = strtok(str, delim);
       while( token != NULL ) 
       {
            res = (char **) realloc(res, (i + 1) * sizeof(char *));
            res[i] = token;
            i++;
          token = strtok(NULL, delim);
       }
       *array = res;
       *length = i;
      return 1;
    }
    
    int main()
    {
        int i;
        int c = 0;
        char **arr = NULL;
    
        int count =0;
    
        char str[80] = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
        c = dtmsplit(str, ",", &arr, &count);
        printf("Found %d tokens.\n", count);
    
        for (i = 0; i < count; i++)
            printf("string #%d: %s\n", i, arr[i]);
    
       return(0);
    }
    

    Result:

    Found 12 tokens.
    string #0: JAN
    string #1: FEB
    string #2: MAR
    string #3: APR
    string #4: MAY
    string #5: JUN
    string #6: JUL
    string #7: AUG
    string #8: SEP
    string #9: OCT
    string #10: NOV
    string #11: DEC
    

提交回复
热议问题