C - split string into an array of strings

后端 未结 2 1852
囚心锁ツ
囚心锁ツ 2020-11-27 03:42

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 contain         


        
2条回答
  •  离开以前
    2020-11-27 03:56

    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.

    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)
    

提交回复
热议问题