【问题标题】:How to split char pointer array into two new char pointer array with delimiters?如何将 char 指针数组拆分为两个带有分隔符的新 char 指针数组?
【发布时间】:2014-03-30 19:58:01
【问题描述】:

我目前在 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);

}

**

【问题讨论】:

    标签: c++ arrays pointers


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 有没有一种方法可以用我最初使用的数组来实现它,因为我需要这些数组中的数据,所以我可以调用 unix 命令 execvp(const char *file, char *const argv []),它接受这些参数。
    • @user3098478 更新帖子
    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 2021-01-26
    • 2015-10-26
    • 2011-04-02
    • 1970-01-01
    • 2018-10-06
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多