Ç - 字符串分割到字符串数组 [英] C - split string into an array of strings

查看:173
本文介绍了Ç - 字符串分割到字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不完全知道如何在C做到这一点:

I'm not completely sure how to do this in 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?

推荐答案

既然你已经看着 strtok的只是继续沿着相同的路径和利用空间分割你的字符串()作为分隔符,然后使用一些如的realloc 来增加含有元素的数组的大小传递给 execvp

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的将修改传递给它的字符串。如果你不希望这样的事情发生,你需要让原始字符串的一个副本,使用的strcpy 或类似的功能。

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.

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)

这篇关于Ç - 字符串分割到字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆