數組我不完全知道如何在C這樣做:Ç - 字符串分割成字符串
char* curToken = strtok(string, ";");
//curToken = "ls -l" we will say
//I need a array of strings containing "ls", "-l", and NULL for execvp()
我怎麼會去這樣做呢?
數組我不完全知道如何在C這樣做:Ç - 字符串分割成字符串
char* curToken = strtok(string, ";");
//curToken = "ls -l" we will say
//I need a array of strings containing "ls", "-l", and NULL for execvp()
我怎麼會去這樣做呢?
既然你已經看過成strtok
只是繼續沿着相同的路徑和使用空間(' '
)作爲分隔符分割你的字符串,那麼使用的東西作爲realloc
增加含有的元素數組的大小要傳遞給execvp
。
請參閱下面的示例,但請記住strtok
將修改傳遞給它的字符串。如果您不希望發生這種情況,則需要使用strcpy
或類似功能複製原始字符串。
char str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;
/* split string and append tokens to 'res' */
while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);
if (res == NULL)
exit (-1); /* memory allocation failed */
res[n_spaces-1] = p;
p = strtok (NULL, " ");
}
/* realloc one extra element for the last NULL */
res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;
/* print the result */
for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);
/* free the memory allocated */
free (res);
res[0] = ls
res[1] = -l
res[2] = (null)
Here is an example of how to use strtok從MSDN借來的。
和相關的位,你需要多次調用它。 token
char *是你可以填充到數組中的部分(你可以指出這部分)。
char string[] = "A string\tof ,,tokens\nand some more tokens";
char seps[] = " ,\t\n";
char *token;
int main(void)
{
printf("Tokens:\n");
/* Establish string and get the first token: */
token = strtok(string, seps);
while(token != NULL)
{
/* While there are tokens in "string" */
printf(" %s\n", token);
/* Get next token: */
token = strtok(NULL, seps);
}
}
如果要基於空格進行拆分,爲什麼要指定';'作爲分隔符? –
例如:string =「ls -l; date; set + v」 – Jordan