2012-06-25 211 views
31

数组我不完全知道如何在C这样做:Ç - 字符串分割成字符串

char* curToken = strtok(string, ";"); 
//curToken = "ls -l" we will say 
//I need a array of strings containing "ls", "-l", and NULL for execvp() 

我怎么会去这样做呢?

+4

如果要基于空格进行拆分,为什么要指定';'作为分隔符? –

+2

例如:string =“ls -l; date; set + v” – Jordan

回答

49

既然你已经看过成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) 
+1

@JordanCarney很高兴能为您服务。 –

+0

@FilipRoséen-refp你可以在打印和释放内存之前解释最后一个代码块:'/ * realloc最后一个NULL * /'的一个额外元素吗?我很难理解它 – Abdul

+0

@Abdul我相信通常每个数组的末尾都有一个空字符,以便计算机可以区分两个不同的数组。 – Charles

6

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

我明白这一点,但这并没有给我一个来自令牌的字符串数组。我想我不明白它的具体部分。 – Jordan

+0

为什么'token = strtok(NULL,seps);'?为什么'NULL'? – Charles

+0

@ c650查看MSDN的链接页面,后续调用需要'NULL'。 –