102. Implement a Simple Shell Command Parser

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

// Parse line and print each word (token) on a new line
void parse_shell_input(char *line) {
    int i = 0;
    int in_token = 0;

    while (line[i] != '\0' && line[i] != '\n') {
        if (isspace(line[i])) {
            if (in_token) {
                putchar('\n'); // End of a word
                in_token = 0;
            }
        } else {
            putchar(line[i]);
            in_token = 1;
        }
        i++;
    }

    if (in_token) {
        putchar('\n'); // End last token
    }
}

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

    parse_shell_input(line);
    return 0;
}

Why This Matters in Firmware?

  • CLI or shell parsers are used in bootloaders, diagnostic shells, or debug interfaces
  • You may not have access to strtok() or dynamic memory
  • Knowing how to parse space-separated strings builds string handling mastery

Logic Summary

  • Read characters one by one
  • Print characters until a space is hit
  • Print newline when token ends
  • Skip multiple spaces

     
Loading...

Input

led set 3 on

Expected Output

led set 3 on