【问题标题】:C - split string into an array of stringsC - 将字符串拆分为字符串数组
【发布时间】:2012-06-27 06:08:08
【问题描述】:

我不完全确定如何在 C 中做到这一点:

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

我该怎么做呢?

【问题讨论】:

  • 如果要按空格分割,为什么要指定;作为分隔符?
  • 例如:string = "ls -l; date; set +v"

标签: c c-strings


【解决方案1】:

既然您已经查看了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)

【讨论】:

  • @JordanCarney 很高兴为您服务。
  • @FilipRoséen-refp 你能解释一下打印和释放内存之前的最后一个代码块,/* realloc one extra element for the last NULL */吗?我很难理解它
  • @Abdul 我相信通常每个数组的末尾都有一个空字符,以便计算机可以区分两个不同的数组。
  • 如果我将它包装到一个函数中并返回 res 指针,我会在释放分配给 res 的指针后收到警告,说:warning: attempt to free a non-heap object [-Wfree-nonheap-object]。您对原因有任何见解吗?
【解决方案2】:

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

【讨论】:

  • 我明白这一点,但这并没有给我来自令牌的字符串数组。我想我不明白其中的具体部分。
  • 为什么是token = strtok(NULL, seps);?为什么是NULL
  • @c650 查看MSDN的链接页面,后续调用需要NULL
  • 啊,是的,我用谷歌搜索了很多,发现strtok() 使用静态变量来保存它的位置。
猜你喜欢
  • 1970-01-01
  • 2012-02-22
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
相关资源
最近更新 更多