All submissions

Implement a Simple Shell Command Parser

Code

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

void parse_shell_input(char *line) {
    char tokens[10][10];
    int row = 0; 
    int column = 0;
    int num_tokens = 0;
    char *ptr = line; 

    while(*ptr != '\0'){

        if(*ptr == ' '){

            tokens[row][column] = '\0';
            num_tokens++;
            column = 0; 
            row++;

            while(*ptr == ' '){
                ptr++;
            }
        }
        else{

            tokens[row][column] = *ptr;
            column++;
            ptr++;
            
        }
        
        if(*ptr == '\0'){
          tokens[row][column] = '\0';
          num_tokens++;
        }          
    }
    
    for(int i = 0; i < num_tokens; i++){
      printf("%s\n", tokens[i]);  
    }
}

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

    parse_shell_input(line);
    return 0;
}

Solving Approach

Prepared  a token holder in this case  a 2D array. 

I copy the char pointer that will be pass to our function in order to keep the original reference memory of the string. With a single pointer I started parsing all the non ' ' characters and kept adding them into the 2D array. I kept track of rows and columns for when a character was added or when a space was encounter. To handle the last string i keep a condition at the end to terminate the last token appropriately. 

Important note which is the soul of this challenge is to start scanning or parsing after all the spaces from string are gone until the next non-space char appears, for that I added a mini while loop to move the pointer until it encounters a non-space char, therefore start scanning again.  

 

Loading...

Input

led set 3 on

Expected Output

led set 3 on