Skip to content
Snippets Groups Projects
Commit 6e59028c authored by jf3g19's avatar jf3g19
Browse files

Initial commit

parents
No related branches found
No related tags found
No related merge requests found
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char** string_split(char* input, char delim)
{
char** split_strings = malloc(sizeof(char*));
char* charPtr;
size_t split_idx = 0;
size_t num_allocated_strings = 1;
size_t extend = 0;
for(charPtr = input; *charPtr != '\0'; ++charPtr)
{
if(*charPtr == delim || *(charPtr+1) == '\0')
{
if(*(charPtr+1) == '\0') extend = 1; //extend the range by one for the null byte at the end
char* string_element = calloc(1, sizeof(char));
for(size_t i = 0; input != charPtr+extend; ++input, ++i)
{
if(string_element[i] == '\0')
{
//allocate another char and add a null byte to the end
string_element = realloc(string_element, sizeof(char) * (strlen(string_element) + 1));
string_element[i+1] = '\0';
}
string_element[i] = *input;
}
split_strings[split_idx++] = string_element;
num_allocated_strings++;
//allocate another c-string if we're not at the end of the input
split_strings = realloc(split_strings, sizeof(char*) * num_allocated_strings);
//skip over the delimiter
input++;
extend = 0;
}
}
free(charPtr);
free(input);
return split_strings;
}
int main()
{
char* str = "what day is it today?";
char delim = ' ';
char** split = string_split(str, delim);
printf("split: %s\n", split[0]);
printf("split: %s\n", split[1]);
printf("split: %s\n", split[2]);
printf("split: %s\n", split[3]);
printf("split: %s\n", split[4]);
return 1;
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment