Split string with delimiters in C

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

    This optimized method create (or update an existing) array of pointers in *result and returns the number of elements in *count.

    Use "max" to indicate the maximum number of strings you expect (when you specify an existing array or any other reaseon), else set it to 0

    To compare against a list of delimiters, define delim as a char* and replace the line:

    if (str[i]==delim) {
    

    with the two following lines:

     char *c=delim; while(*c && *c!=str[i]) c++;
     if (*c) {
    

    Enjoy

    #include 
    #include 
    
    char **split(char *str, size_t len, char delim, char ***result, unsigned long *count, unsigned long max) {
      size_t i;
      char **_result;
    
      // there is at least one string returned
      *count=1;
    
      _result= *result;
    
      // when the result array is specified, fill it during the first pass
      if (_result) {
        _result[0]=str;
      }
    
      // scan the string for delimiter, up to specified length
      for (i=0; i

    Usage example:

    #include 
    
    int main(int argc, char **argv) {
      char *str="JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
      char **result=malloc(6*sizeof(char*));
      char **result2=0;
      unsigned long count;
      unsigned long count2;
      unsigned long i;
    
      split(strdup(str),strlen(str),',',&result,&count,6);
      split(strdup(str),strlen(str),',',&result2,&count2,0);
    
      if (result)
      for (i=0; i

提交回复
热议问题