Implement a Simple Shell Command Parser

Code

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

void parse_shell_input(char *line) {
    // Your logic here
    char tokens[10][20];
    int count = 0;
    bool flag_init =0;

    int k=0;
    

    for( int i=0; line[i] !='\0'; i++)
    {
        if(line[i] == ' ' && line[i+1] != ' ' )
        {
            if(i==0)
            flag_init =1;
            else
            flag_init=0;

            if(!flag_init)
            {
            tokens[count][k] = '\0';   
            count += 1;
            k=0;
            }      
            
        }
         else if(line[i] != ' ' && line[i] != '\n' )
         tokens[count][k++] = line[i];
              
    }
     tokens[count][k] = '\0';  // terminate last token
     count += 1; //to include last word
    
    //printf("%d", count);

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

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

       // Remove newline
    int i = 0;
    while (line[i]) {
        if (line[i] == '\n') { line[i] = '\0'; break; }
        i++;
    }
    parse_shell_input(line);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

led set 3 on

Expected Output

led set 3 on