Implement a Simple Shell Command Parser

Code

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

void parse_shell_input(char *line) {
    char token[101];
    int i = 0, j = 0;

    while (line[i] != '\0') {
        if (line[i] != ' ' && line[i] != '\n') {
            token[j++] = line[i];
        } else {
            if (j > 0) {
                token[j] = '\0';
                printf("%s\n", token);
                j = 0;
            }
            // Skip multiple spaces
        }
        i++;
    }

    // Print last token if any
    if (j > 0) {
        token[j] = '\0';
        printf("%s\n", token);
    }
}

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

    parse_shell_input(line);
    return 0;
}

Solving Approach

Step-by-Step Solving Algorithm

  1. Read input line
    • Use fgets() to read up to 100 characters into a buffer
    • Remove the trailing newline ('\n') if present
  2. Initialize indices
    • i: scans the input character by character
    • j: builds each token into a temporary buffer
  3. Loop through each character
    • If the character is not a space:
      • Copy it into token[j++]
    • If the character is a space:
  • If j > 0, terminate the token with '\0', print it, and reset j = 0
  • Skip consecutive spaces
  1. After the loop ends
  • If j > 0, print the final token

 

 

 

 

Upvote
Downvote
Loading...

Input

led set 3 on

Expected Output

led set 3 on