Implement a Simple Shell Command Parser

Code

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

void parse_shell_input(char *line) {
    // Your logic here
    if (!line || *line == '\0') return;

    char *token[15];
    int count = 0;
    char *p = line;

    while (*p != '\0' && count < 15)
    {
        // 1. Bỏ qua các dấu cách thừa ở trước token
        while (*p == ' ') p++;

        // Nếu chạm cuối chuỗi sau khi bỏ qua dấu cách thì dừng
        if (*p == '\0') break;

        // 2. Lưu địa chỉ bắt đầu của token
        token[count++] = p;

        // 3. Tìm đến dấu cách tiếp theo hoặc cuối chuỗi để "chặt"
        while (*p != '\0' && *p != ' ') p++;

        if (*p == ' ')
        {
            *p = '\0'; // Kết thúc token tại đây
            p++;       // Nhảy sang ký tự tiếp theo để tìm token mới
        }
    }

    // In kết quả
    for(int i = 0; i < count; i++)
    {
        printf("%s\n", token[i]);
    }
}

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