103. Implement a Simple Shell Command Parser

Back To All Submissions
Previous Submission
Next Submission

Code

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

void parse_shell_input(char *line) {
    // Your logic here
    int i = 0, c = 0, r = 0;
    char tokens[10][20];

    while(line[i] != '\0' && line[i] != '\n'){
        if(line[i] != ' '){
            if(c < 19){
                tokens[r][c] = line[i];
                c++;
            }
        }
        else{
            if(c > 0){
                tokens[r][c] = '\0';
                c = 0;
                r++;
            } 
        }
        i++;
    }

    if(c > 0){
        tokens[r][c] = '\0';
        r++;
    }

    for(int j = 0; j < r; j++){
        printf("%s\n",tokens[j]);
    }
}

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

    parse_shell_input(line);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote