103. Implement a Simple Shell Command Parser

Back To All Submissions
Previous Submission
Next Submission

Code

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

void splitstr(char* str , char delamieter, char ret_str[100][100],int& cnt)
{
     //char* ret_list[100]  = {0};
    int i = 0;
    int cmd_row = 0;
    int cmd_col = 0;
    while(str[i] == ' '){i++;} //leading space
    while(str[i] != '\0')
    {
        if(str[i] == ' ')
        {
           // i++;
            while(str[i] == ' '){i++;}
            ret_str[cmd_row][cmd_col] = '\0';
            cmd_col = 0;
            cmd_row++; 
            continue;

        }
        ret_str[cmd_row][cmd_col]= str[i];
        cmd_col++;
        i++;
    }
    ret_str[cmd_row][cmd_col] = '\0';
    cnt = cmd_row+1;
}  


void parse_shell_input(char *line) {
    // Your logic here
    // char* token = strtok(line," ");
    
     char cmd [100][100] ={{0}}; 
     int cnt =0;
    // int i=0;
    // while(token != NULL)
    // {
    //     printf("%s\n" , token);
    //     token = strtok(NULL , " ");
    // }
    splitstr(line ,' ' ,cmd, cnt);
    for(int j= 0; j < cnt; j++)
    {
        printf("%s\n" , cmd[j]);
    }
}

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

    parse_shell_input(line);
    return 0;
}

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote