2014-03-30 67 views
0

我目前有一個char *命令[SIZE]數組,主要是通過接受用戶輸入來填充。一個可以填寫的例子是{「ls」,「-1」,「|」 「分類」}。我想把它作爲一個函數的參數,並使用分隔符「|」將它分成兩個數組(char * command1 [SIZE],char * command2 [SIZE])。因此,char * command1 [SIZE]包含{「ls」和「-l」},並且char * command2 [SIZE]包含{「sort」}。 Command1和Command2不應包含分隔符。如何將字符指針數組拆分爲兩個帶分隔符的新字符指針數組?

這裏是我下面的代碼的一部分...

** 無效executePipeCommand(字符*命令){

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主要(無效){

char *command[SIZE]; 

    //take in user input... 

    executePipeCommand(command); 

}

**

回答

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; 
+0

有沒有一種方法,我可以用我本來用,因爲我需要這些陣列中的數據,所以我可以調用UNIX命令execvp陣列實現它(const char *文件,char * const argv []),它接受這些參數。 – simhuang

+0

@ user3098478更新後的帖子 –

+0

感謝您的幫助! – simhuang