C-podziel ciąg na tablicę ciągów

Nie jestem do końca pewien jak to zrobić w C:

char* curToken = strtok(string, ";");
//curToken = "ls -l" we will say
//I need a array of strings containing "ls", "-l", and NULL for execvp()
Jak miałbym to zrobić?
 33
Author: Jordan, 2012-06-26

2 answers

Ponieważ już zajrzałeś do strtok po prostu przejdź tą samą ścieżką i Podziel swój łańcuch za pomocą spacji (' ') jako ogranicznika, a następnie użyj czegoś jako realloc, Aby zwiększyć rozmiar tablicy zawierającej elementy, które mają być przekazane do execvp.

Zobacz poniższy przykład, ale pamiętaj, że strtok zmodyfikuje przekazywany do niego łańcuch znaków. Jeśli nie chcesz, aby tak się stało, musisz wykonać kopię oryginalnego ciągu znaków, używając strcpy lub podobnej funkcji.

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)
 53
Author: Filip Roséen - refp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-25 23:16:08

Oto przykład użycia strtok zapożyczonego z MSDN.

I odpowiednie bity, musisz wywołać je wiele razy. Znak token * jest częścią, którą umieścisz w tablicy (możesz ją rozgryźć).

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 );
    }
}
 6
Author: Chris O,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-06-25 23:05:17