C - tokenise array of chars

2019-09-16 06:13发布

问题:

I'm trying to parse a single line so that each word after a whitespace is saved separately as char into an array. I tried it in number of ways, this is one of them...

char space[] = " ";
char* token;  
token = strtok(input,space);
char array[50];


while (token !=NULL ) {
    char a;
    sscanf(token,"%s", &a);
    array[i] = a;
    token = strtok(NULL, space);
    printf("\nTOKEN: %s", a); 
    int++;
}

回答1:

char a;
sscanf(token,"%s", &a);

That's wrong, you are telling sscanf to read a string yet you give it a single char. A "word" does not fit in a single char. Its not really clear what you are trying to do, perhaps you want something like this:

char* array[50];

int i = 0;
for( char* token = strtok( input, " " ); token != NULL && i < 50; token = strotok( NULL, " " ) )
{
    array[ i ] = token;
    ++i;
}

This will fill array with pointers to each substring within input separated by spaces. The original contents will remain on input, the array only points into it.



回答2:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef char** StringArray;

StringArray split(const char *str, const char *delimiter){
    char *text, *p, *first, **array;
    int c;
    StringArray ret;

    text=strdup(str);
    if(text==NULL) return NULL;
    for(c=0,p=text;NULL!=(p=strtok(p, delimiter));p=NULL, c++)//count item
        if(c==0) first=p; //first token top

    ret=(StringArray)malloc(sizeof(char*)*(c+1));//+1 for NULL
    if(ret==NULL){
        free(text);
        return NULL;
    }
    strcpy(text, str+(first-text));//skip until top token
    array=ret;

    for(p=text;NULL!=(p=strtok(p, delimiter));p=NULL){
        *array++=p;
    }
    *array=NULL;
    return ret;
}

void free4split(StringArray sa){
    char **array=sa;

    if(sa!=NULL){
        free(array[0]);//for text
        free(sa);      //for array
    }
}

int main(void){
    char *str = "The quick brown fox jumps over the lazy dog";
    StringArray words;
    char **wk;

    words = split(str, " \t\r\n");

    for(wk = words; *wk ;wk++){
        printf("%s\n", *wk);
    }

    free4split(words);
    return 0;
}
/* result
The
quick
brown
fox
jumps
over
the
lazy
dog
*/


标签: c parsing