簡體   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