Parse string into array based on spaces or “double quotes strings”

前端 未结 4 627
庸人自扰
庸人自扰 2021-01-21 09:29

Im trying to take a user input string and parse is into an array called char *entire_line[100]; where each word is put at a different index of the array but if a part of the str

4条回答
  •  旧巷少年郎
    2021-01-21 10:15

    Torek's parts of parsing code are excellent but require little more work to use.

    For my own purpose, I finished c function.
    Here I share my work that is based on Torek's code.

    #include 
    #include 
    #include 
    size_t split(char *buffer, char *argv[], size_t argv_size)
    {
        char *p, *start_of_word;
        int c;
        enum states { DULL, IN_WORD, IN_STRING } state = DULL;
        size_t argc = 0;
    
        for (p = buffer; argc < argv_size && *p != '\0'; p++) {
            c = (unsigned char) *p;
            switch (state) {
            case DULL:
                if (isspace(c)) {
                    continue;
                }
    
                if (c == '"') {
                    state = IN_STRING;
                    start_of_word = p + 1; 
                    continue;
                }
                state = IN_WORD;
                start_of_word = p;
                continue;
    
            case IN_STRING:
                if (c == '"') {
                    *p = 0;
                    argv[argc++] = start_of_word;
                    state = DULL;
                }
                continue;
    
            case IN_WORD:
                if (isspace(c)) {
                    *p = 0;
                    argv[argc++] = start_of_word;
                    state = DULL;
                }
                continue;
            }
        }
    
        if (state != DULL && argc < argv_size)
            argv[argc++] = start_of_word;
    
        return argc;
    }
    void test_split(const char *s)
    {
        char buf[1024];
        size_t i, argc;
        char *argv[20];
    
        strcpy(buf, s);
        argc = split(buf, argv, 20);
        printf("input: '%s'\n", s);
        for (i = 0; i < argc; i++)
            printf("[%u] '%s'\n", i, argv[i]);
    }
    int main(int ac, char *av[])
    {
        test_split("\"some text in quotes\" plus four simple words p\"lus something strange\"");
        return 0;
    }
    

    See program output:

    input: '"some text in quotes" plus four simple words p"lus something strange"'
    [0] 'some text in quotes'
    [1] 'plus'
    [2] 'four'
    [3] 'simple'
    [4] 'words'
    [5] 'p"lus'
    [6] 'something'
    [7] 'strange"'

提交回复
热议问题