Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - split string into an array of strings

Tags:

c

c-strings

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?

like image 430
Jordan Avatar asked Jun 25 '12 23:06

Jordan


People also ask

How do you split a string into an array?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How can I split a string in C?

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

Can we convert string to array in C?

1. The c_str() and strcpy() function in C++ C++ c_str() function along with C++ String strcpy() function can be used to convert a string to char array easily. The c_str() method represents the sequence of characters in an array of string followed by a null character ('\0').

What is strtok in C?

The C function strtok() is a string tokenization function that takes two arguments: an initial string to be parsed and a const -qualified character delimiter. It returns a pointer to the first character of a token or to a null pointer if there is no token.


1 Answers

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) 
like image 59
Filip Roséen - refp Avatar answered Sep 29 '22 10:09

Filip Roséen - refp