繁体   English   中英

如何使用定界符将char指针数组拆分为两个新的char指针数组?

[英]How to split char pointer array into two new char pointer array with delimiters?

我目前在main中有一个char * command [SIZE]数组,可以通过接收用户输入来填充。 可以填写的示例是{“ ls”,“-1”,“ |” “分类”}。 我想将其作为函数的参数,并使用定界符“ |”将其分成两个数组(char * command1 [SIZE],char * command2 [SIZE])。 因此char * command1 [SIZE]包含{“ ls”和“ -l”},而char * command2 [SIZE]包含{“ sort”}。 Command1和Command2不应包含定界符。

这是我下面的代码的一部分...

** void executePipeCommand(char * command){

  char *command1[SIZE];
  char *command2[SIZE];


 //split command array between the delimiter for further processing. (the delimiter 
   is not needed in the two new array)

}

int main(void){

  char *command[SIZE];

  //take in user input...

  executePipeCommand(command);

}

**

适用于任意数量的拆分令牌,您可以选择拆分令牌。

std::vector<std::vector<std::string>> SplitCommands(const std::vector<std::string>& commands, const std::string& split_token)
{
    std::vector<std::vector<std::string>> ret;
    if (! commands.empty())
    {
        ret.push_back(std::vector<std::string>());
        for (std::vector<std::string>::const_iterator it = commands.begin(), end_it = commands.end(); it != end_it; ++it)
        {
            if (*it == split_token)
            {
                ret.push_back(std::vector<std::string>());
            }
            else
            {
                ret.back().push_back(*it);
            }
        }
    }
    return ret;
}

转换为所需格式

std::vector<std::string> commands;
char ** commands_unix;
commands_unix = new char*[commands.size() + 1]; // execvp requires last pointer to be null
commands_unix[commands.size()] = NULL;
for (std::vector<std::string>::const_iterator begin_it = commands.begin(), it = begin_it, end_it = commands.end(); it != end_it; ++it)
{
    commands_unix[it - begin_it] = new char[it->size() + 1]; // +1 for null terminator
    strcpy(commands_unix[it - begin_it], it->c_str());
}


// code to delete (I don't know when you should delete it as I've never used execvp)
for (size_t i = 0; i < commands_unix_size; i++)
{
    delete[] commands_unix[i];
}
delete[] commands_unix;

暂无
暂无

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

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