我目前在main中有一个char *命令[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);
}
**
答案 0 :(得分:0)
适用于任意数量的拆分令牌,您可以选择拆分令牌。
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;