Código: Seleccionar todo
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char **substring_ptr;
int number_of_substrings;
} split_struct;
int _strlen(char*);
split_struct *split(char *,char *,int,int);
int main() {
split_struct *str_info;
char str[] = "STR1#DLM#STR2#DLM#STR3#DLM#STR4";
char sep[] = "#DLM#";
str_info = split(str,sep,_strlen(str),_strlen(sep));
for(int y=0;y<str_info->number_of_substrings;y++)
{printf("%s\n", str_info->substring_ptr[y]);}
getchar();
return 0;
}
int _strlen(char *pstr) {
int i=0;
while(*(pstr++)!='\0') i++;
return i;
}
split_struct *split(char *string,char *sep, int str_len, int sep_len) {
split_struct *retvalue;
retvalue = (split_struct*)malloc(sizeof(split_struct));
int ptr_block=0, chr=0, bool_end=0;
char **buffer = (char**)malloc(sizeof(char*));
*buffer = (char*)malloc(sizeof(char*));**buffer=0;
char *tok = (char*)malloc(sep_len*sizeof(char));
for(int z=0;z<str_len;z++) {
for(int n=0;n<sep_len&&!bool_end;n++)
tok[n]=(z+n<str_len)?string[z+n]:bool_end=1;
int cmp_xy=0;for(int y=0;y<sep_len;y++)if(tok[y]!=sep[y]) cmp_xy=1;
if (cmp_xy || bool_end) {
buffer[ptr_block][chr++] = string[z];
buffer[ptr_block] = (char*)realloc(buffer[ptr_block],chr*sizeof(char*));
buffer[ptr_block][chr] = 0;
} else {
buffer = (char**)realloc(buffer,(++ptr_block+1)*sizeof(char*));
buffer[ptr_block] = (char*)malloc(sizeof(char*));**(buffer+ptr_block)=0;
chr=0;z+=sep_len-1;
}
}
free(tok);
retvalue->substring_ptr = buffer;
retvalue->number_of_substrings = ptr_block+1;
return retvalue;
}
Saludos!