This function takes a string of arbitrary length and splits it into an array of strings using a delimiter. The return value is an array of strings.
Test the code in main and you can change the delimiter if necessary.
/* Author: Jeremy Heyno
* Licensed under GPLv3*/
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
char **splittedString(const char *string, char delimiter)
{
/* Count of delimiters*/
int tokenCounter = 0;
/* How many tokenized strings*/
size_t arrCounter = 0;
/* String pointer*/
const char *ptr = string;
/* Count amount of delimiters*/
while(*ptr)
{
if(*ptr == delimiter)
{
tokenCounter++;
}
ptr++;
}
/* Do the malloc */
char **inputArray = malloc((tokenCounter+1) * sizeof(char*));
/* Pointer to move to end of tokenized string*/
const char *incrementPtr=string;
ptr=string;
/* How many tokens are behind us*/
int tokens = 0;
/* Index where to copy*/
int i = 0;
/* Enter the loop to go through the string */
while(*incrementPtr)
{
/* Character indexes*/
arrCounter++;
incrementPtr++;
/* Hit the delimiter char*/
if(*incrementPtr == delimiter)
{
/* calloc the necessary character count */
inputArray[i] = calloc((arrCounter+1), sizeof(char));
/* After first token have to move one further for start of next tokenized string*/
if(tokens == 0)
{
strncpy(inputArray[i], ptr, arrCounter);
}
else
{
strncpy(inputArray[i], (ptr+1),(arrCounter-1));
}
i++;
ptr = incrementPtr;
/* Reset arrays and move tokens by one*/
arrCounter=0;
tokens++;
/* Break to deal with last token*/
if(tokens == tokenCounter)
{
break;
}
}
}
/* Deal with the last token */
while(*incrementPtr)
{
arrCounter++;
incrementPtr++;
}
inputArray[tokenCounter] = calloc((arrCounter+1),sizeof(char));
strncpy(inputArray[tokenCounter], (ptr+1), arrCounter);
return (inputArray);
}
int main(void)
{
const char *string = "This is a string with spaces and other stuff";
char delimiter = ' ';
char **inputArray = splittedString(string, delimiter);
int delimCounter=0;
while(*string)
{
if (*string == delimiter)
{
delimCounter++;
}
string++;
}
for(int j = 0; j <= delimCounter; j++)
{
printf("%s\n",inputArray[j]);
}
for(int k = 0; k <= delimCounter; k++)
{
free(inputArray[k]);
}
free(inputArray);
}