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

updates

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