Implement a Simple Shell Command Parser

Code

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

void parse_shell_input(char *line) {
    // Your logic here
    if (!line || line[0] == '\0') return;

    char w[101][101];
    int r = 0, c = 0;
    int is_word = 0;

    char *ptr = line;
    while (*ptr != '\0') {
        if (*ptr == ' ') {
            if (is_word) {
                w[r][c] = '\0';
                r++;
                c = 0;
                is_word = 0;
                if (r >= 101) break;
            }
        } else {
            if (c < 100) {
                w[r][c] = *ptr;
                c++;
                is_word = 1;
            }
        }
        ptr++;
    }
    if (c < 101) {
        w[r][c] = '\0';
    }

    for (int i = 0; i <= r; i++) {
        printf ("%s\n", w[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