Question: Write a function in C that splits a string of characters depending on a separator. The function will written a custom struct array. Example usage

Write a function in C that splits a string of characters depending on a separator. The function will written a custom struct array.
Example usage should return an array of each substring.
// possibly incorrect test usage:
int main(){
char* test_str = "abc def gh-!";
char* test_sep ="-";
string_array *res =(string_array*)malloc(sizeof(string_array));
res = my_split(test_str, test_sep); // should return ["abd def gh","!"]
printf("%s
", res->array);
free(res);
return 0;
}
// my_split.c
typedef struct s_string_array
{
int size;
int subs;
char** array;
} string_array;
#endif
string_array* my_split(char* str, char* c_sep)
{
string_array* arr =(string_array*)malloc(sizeof(string_array));
arr->size =0;
arr->subs =0;
arr->array = NULL;
const char *tmp_str;
tmp_str = str;
while (*tmp_str)
{
while (tmp_str == c_sep)++tmp_str;
if(*tmp_str)
{
++arr->size;
}
while (*++tmp_str !='\0' && tmp_str != c_sep);
}
int found =1;
while (found && *str)
{
while (str == c_sep)++str;
if (*str)
{
const char *m1= str; // first match
while (*++str !='\0' && str != c_sep);
size_t sz = str - ml;
char *m_cur = malloc(sz+1);
found = m_cur != NULL;
if (found)
{
char **tmp = realloc(arr->array, (arr->subs+1)* sizeof(char *));
found = tmp != NULL;
if(found)
{
arr->array = tmp;
strncpy(m_cur, ml, sz);
m_cur[sz]='\0';
arrr->array[arr->subs++]= m_cur;
} else {
free(m_cur);
}
}
}
}
return arr;
}
Write a function in C that splits a string of

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!