2012-06-25 63 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'。 –