繁体   English   中英

C - 将字符串拆分为字符串数组

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

我不完全确定如何在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)

这是一个如何使用从MSDN借来的strtok的例子

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM