Implement a Simple Shell Command Parser

Code

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

void parse_shell_input(char *line) {
    int i = 0;
    char token[20];
    int pos = 0;

    while (line[i] != '\0' && line[i] != '\n') {
        // Bỏ qua khoảng trắng ở đầu giữa các từ
        while (line[i] == ' ' || line[i] == '\t') {
            i++;
        }

        // Nếu là ký tự hợp lệ (không phải khoảng trắng hay kết thúc chuỗi)
        if (line[i] != '\0' && line[i] != '\n') {
            pos = 0;
            // Lấy 1 token (một từ)
            while (line[i] != ' ' && line[i] != '\t' && line[i] != '\0' && line[i] != '\n') {
                if (pos < 19) {
                    token[pos++] = line[i];
                }
                i++;
            }
            token[pos] = '\0';
            printf("%s\n", token);
        }
    }
}

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