Code Snippet: string split in c++ (c syntax)

Below code snippet useful while splitting string (char*) .

 

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

int split (const char *str, char c, char ***arr)
{
 int count = 1;
 int token_len = 1;
 int i = 0;
 char *p;
 char *t;

 p = str;
 while (*p != '\0')
 {
 if (*p == c)
 count++;
 p++;
 }

 *arr = (char**) malloc(sizeof(char*) * count);
 if (*arr == NULL)
 exit(1);

 p = str;
 while (*p != '\0')
 {
 if (*p == c)
 {
 (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
 if ((*arr)[i] == NULL)
 exit(1);

 token_len = 0;
 i++;
 }
 p++;
 token_len++;
 }
 (*arr)[i] = (char*) malloc( sizeof(char) * token_len );
 if ((*arr)[i] == NULL)
 exit(1);

 i = 0;
 p = str;
 t = ((*arr)[i]);
 while (*p != '\0')
 {
 if (*p != c && *p != '\0')
 {
 *t = *p;
 t++;
 }
 else
 {
 *t = '\0';
 i++;
 t = ((*arr)[i]);
 }
 p++;
 }
 return count;
}

int main(void) {
 
 char* strToSplit ="REPLY id, login, cmd, volume, symbol, price, bid/ask, rate-id, status, message";
 int i;
 int c = 0;
 char **splittedarr = NULL;
 c = split(strToSplit, ',', ;&splittedarr)

 printf("found %d occurrence.\n", c);

 for (i = 0; i < c; i++)
 printf("string #%d:%s\n", i, splittedarr[i]);
 return 0;
}


Output
found 10 occurence.
string #0:REPLY id
string #1: login
string #2: cmd
string #3: volume
string #4: symbol
string #5: price
string #6: bid/ask
string #7: rate-id
string #8: status
string #9: message