C - 將字符串拆分為字符串數組

[英]C - split string into an array of strings


I'm not completely sure how to do this in C:

我不完全確定如何在C中執行此操作:

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

How would I go about doing this?

我該怎么做呢?

2 个解决方案

#1


52  

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

既然你已經查看了strtok,只需繼續沿着相同的路徑並使用空格('')作為分隔符拆分你的字符串,然后使用一些東西作為realloc來增加包含要傳遞給execvp的元素的數組的大小。

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

請參閱下面的示例,但請記住,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)

#2


6  

Here is an example of how to use strtok borrowed from MSDN.

這是一個如何使用從MSDN借來的strtok的例子。

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

和相關的位,你需要多次調用它。令牌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 );
    }
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/06/25/ba97c234c10ad4aa5660d276849f0f41.html



 
  © 2014-2022 ITdaan.com 联系我们: