Skip to content
Snippets Groups Projects
Commit 4818415b authored by jf3g19's avatar jf3g19
Browse files

updates

parent 6e59028c
Branches
No related tags found
No related merge requests found
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
char** string_split(char* input, char delim)
char** string_split(char* input, char delim, bool skip_delim)
{
assert(*input != '\0');
char** split_strings = malloc(sizeof(char*));
char* charPtr;
......@@ -20,41 +24,56 @@ char** string_split(char* input, char delim)
for(size_t i = 0; input != charPtr+extend; ++input, ++i)
{
if(string_element[i] == '\0')
if(string_element[i] == '\0')
{
//allocate another char and add a null byte to the end
char* temp = realloc(string_element, sizeof(char) * (strlen(string_element) + 1));
if(temp == NULL)
{
//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';
free(string_element);
free(split_strings);
break;
}
string_element[i] = *input;
string_element = temp;
string_element[i+1] = '\0';
}
string_element[i] = *input;
}
//printf("std: %s\n", string_element);
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);
//allocate another c-string
char** temp = realloc(split_strings, sizeof(char*) * num_allocated_strings);
if(temp == NULL)
{
free(string_element);
free(split_strings);
break;
}
split_strings = temp;
//skip over the delimiter
input++;
//skip over the delimiter if required
if(skip_delim) input++;
extend = 0;
}
}
free(charPtr);
free(input);
split_strings[num_allocated_strings-1] = NULL;
return split_strings;
}
int main()
{
char* str = "what day is it today?";
char delim = ' ';
char** split = string_split(str, delim);
char* str = " the , cat, onthemat";
char delim = ',';
char** split = string_split(str, delim, true);
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]);
for ( char **p = split; *p != NULL; ++p )
{
puts( *p );
}
free(split);
return 1;
return EXIT_SUCCESS;
}
\ 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