-1

I am looking to convert a simple comma separated string like this:

apples, pears, oranges,

into a C String Array(NOT A CHARCHTER ARRAY) similar to the one found here: How do I create an array of strings in C?

I know how to do this in Python and Javascript, but how would I go about creating this in C?

Community
  • 1
  • 1
AgentSpyname
  • 105
  • 1
  • 9
  • First of all, where are you reading the line from? Secondly, What is the maximum number of strings that will be seperated? Lastly, What is the maximum number of characters of the seperated string? – Spikatrix May 30 '15 at 09:24
  • @CoolGuy Im trying to expand on a demo app for the Pebble Watch to better understand how it works. The data comes from a Key **sent from Js**. The total amount of characters would be about 90 including [0]. About 9 Strings separated. – AgentSpyname May 30 '15 at 09:28

1 Answers1

2

Use strtok like the following... arrayOfString will have list of strings.

#include <string.h>
#include <stdio.h>

int main()
{
   char str[80] = "apples, pears, oranges,";
   char* arrayOfString[3];
   const char s[2] = ", ";
   char *token;
   int i=0;
   /* get the first token */
   token = strtok(str, s);

   /* walk through other tokens */
   while( token != NULL ) 
   {
      arrayOfString[i] = token;
      token = strtok(NULL, s);
      i++;
   }

   for(i=0;i<3;i++)
    printf("%s\n", arrayOfString[i]);

   return(0);
}
sabbir
  • 438
  • 3
  • 11