简体   繁体   English

C-strsep分割字符串

[英]C - strsep splitting strings

I created a parseCmd method for my simpleShell program in C, and store each argument before a delimiter whitespace to be stored in my args[] array. 我用C为我的simpleShell程序创建了一个parseCmd方法,并将每个参数存储在要存储在args []数组中的定界符空格之前。 However, I am trying to add arguments with their respective parameters into a linked list, but I am having trouble obtaining them. 但是,我试图将参数及其各自的参数添加到链接列表中,但是我在获取它们时遇到了麻烦。

For example, if I type ls , I want: 例如,如果输入ls ,我想要:

args[0] = "ls";

And when I type ls -l , I want; 当我键入ls -l ,我想要;

args[0] = "ls";
args[1] = "-l";

What I am trying to do here is: if a "-" argument is detected, append it to the previous argument "ls" and save as a separate string "ls -l" to be stored into a linkedList (already implemented). 我在这里尝试做的是:如果检测到“-”参数,请将其附加到上一个参数“ ls”,并另存为单独的字符串“ ls -l”,以存储到linkedList中(已实现)。

Here is my method. 这是我的方法。

void parseCmd(char* cmd, char** args)
{       
    int i;

    for(i = 0; i < MAX_LINE; i++) {
        args[i] = strsep(&cmd, " ");

        if (args[i] != NULL)
            printf("--> %s \n",args[i]);

        if(args[i] == NULL) break;
    }
}

EDIT: 编辑:

I tried the following 我尝试了以下

if (strchr(args[i], '-'))
    printf("--> %s \n", args[i]);

But I am getting a seg fault. 但是我遇到了段错误。

String is an array of characters. 字符串是字符数组。 You realize that args is a char**, so basically it is an array of arrays. 您意识到args是char **,所以基本上它是一个数组数组。 You can check if args entry contains '-', if it is true then you can do a simple string concat and add that value to args. 您可以检查args条目是否包含“-”,如果为true,则可以执行简单的字符串concat并将该值添加到args。 Check the value of the first character of string. 检查字符串的第一个字符的值。

Programmatically, 以编程方式,

if(args[i][0] == '-')
    <Insert code for concatenation>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM