数组我不完全知道如何在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