c - 使用 strtok 分割 c 数组

标签 c strtok

我正在制作一个自定义 C shell,并且当前使用空格分割命令:

(我当前正在做的事情的简化示例)

char *buf[20];
char *tempVar;
tempvar = strtok(buf, " ");

例如:

sleep 5 将分为 sleep5

但是,我也想拆分 & (以创建后台进程)。因此,sleep 5& 将分为 3 个:sleep5&

任何帮助将不胜感激。

最佳答案

您可以使用特定的方法来提取数字,或者直接删除字符&。我想到这里,也许这不是最好的解决方案。希望进一步交流。

char buf[] = "sleep 5&";
char *cmd;
char *arg;
char *tmpArg;
int count = 0;
while (true) {
    if (0 == count) {
        cmd = strtok(buf, " ");
        arg = strtok(NULL, " ");
    } else {
        cmd = strtok(NULL, " ");
        arg = strtok(NULL, " ");
    }
    printf("%s\n", cmd);

    if (NULL != cmd) {
        if (strcmp("sleep", cmd) == 0) {
            if (arg != NULL) {
                // 1. introduce a method to extract digit or
                // 2. using `&` to split the arg again, the shortcoming is that we omit character `&` here.
                for (int i = 0; i < 2; ++i) {
                    if (0 == i) {
                        tmpArg = strtok(arg, "&");
                    } else {
                        tmpArg = strtok(NULL, "&");
                    }
                    printf("%s\n", tmpArg);
                }
            }
        }
    } else {
        break;
    }
    ++count;
}

关于c - 使用 strtok 分割 c 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59313612/

相关文章:

c++ - RAS API。 sizeof(RASDIALPARAMS) 是错误的。错误 632

c - 为什么int类型在BSS段占8字节,在DATA段占4字节

c - 为什么某些 C 字符串库函数(即 strtok)不接受尚未使用 malloc 分配的 char *?

c - 为什么 strtok() 没有正确迭代其 while 循环?

Microsoft Windows 中的 CPU 设备驱动程序

c - Perl XS : What is the meaning of this dumped value for object - t_obj is - $VAR1 = bless( do{\(my $o = 41032464)}, 'Math::Test1' );

c - sscanf - 如果遇到特定字符则提前停止扫描

c - 为什么我的 strcmp() 失败了?

c - strtok 究竟是如何工作的?

c - 从 C 中的 txt 文件中读取和拆分未定义的字符串