Implement a Simple Shell Command Parser

Code

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

void parse_shell_input(char *line) {
    int i = 0;                // index to walk through the string
    int in_word = 0;          // flag to track if we are inside a word

    while (line[i] != '\0') { // loop until end of string
        if (!isspace(line[i])) {   // if current char is not space
            if (!in_word) {        // we are starting a new word
                in_word = 1;       // mark that we are inside a word
            }
            putchar(line[i]);      // print the character
        } else {                   // current char is space or newline
            if (in_word) {         // if we were inside a word
                putchar('\n');     // end the word, print newline
                in_word = 0;       // reset flag
            }
        }
        i++;                       // move to next character
    }

    // If the line ended while still inside a word, print newline
    if (in_word) {
        putchar('\n');
    }
}

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

    parse_shell_input(line);
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

led set 3 on

Expected Output

led set 3 on