c splitting a char* into an char**

后端 未结 4 897
孤城傲影
孤城傲影 2021-01-22 09:20

I\'m reading in a line from a file (char by char, using fgetc()), where all fields(firstname, lastname, ...) are seperated by an ;. What I now want to do is create

4条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-22 09:34

    It may be that Helper Method wants each of the "fields" written to a nul-terminated string. I cannot tell. You can do that with strtok(). However strtok() has problems - it destroys the original string "fed" to it.

    #define SPLIT_ARRSZ 20   /* max possible number of fields */
    char **
    split( char *result[], char *w, const char *delim)
    {
        int i=0;
        char *p=NULL;
        for(i=0, result[0]=NULL, p=strtok(w, delim); p!=NULL; p=strtok(NULL, delim), i++ )
        {
               result[i]=p;
               result[i+1]=NULL;
        }
        return result;
    }
    
    void
    usage_for_split(void)
    {
        char *result[SPLIT_ARRSZ]={NULL};
        char str[]="1;2;3;4;5;6;7;8;9;This is the last field\n";
        char *w=strdup(str);
        int i=0;
        split(result, w, ";\n");
        for(i=0; result[i]!=NULL; i++)
           printf("Field #%d = '%s'\n", i, result[i]);
        free(w);
    }
    

提交回复
热议问题