Implement a Simple Shell Command Parser

Code

#include <stdio.h>
#include <ctype.h>
#include <stdint.h>

void split_string(const char *str, char delimiter, char tokens[10][20], uint8_t *count) {
    int pos = 0;
    for (size_t i=0; i< 200; i++){
        char chr = *(str+i);
        if (chr != delimiter){
            tokens[*count][pos] = chr;
            pos++;
        } else {
            if (pos == 0){
                continue;
            }
            tokens[*count][pos] = '\0';
            pos=0;
            (*count)++;
        }
    }
    (*count)++;
}

void parse_shell_input(char *line) {
    char tokens[10][20];
    uint8_t count = 0;
    split_string(line, ' ', tokens, &count);
    for (size_t i=0; i<count; i++){
        printf("%s\n", tokens[i]);
    }
}

int main() {
    char line[101];
    fgets(line, sizeof(line), stdin);

    parse_shell_input(line);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

led set 3 on

Expected Output

led set 3 on