Función SPLIT con delimitador multicarácter

Iniciado por binary_death, Septiembre 01, 2013, 01:55:52 PM

Tema anterior - Siguiente tema

0 Miembros y 1 Visitante están viendo este tema.

Función SPLIT que permite partir una cadena en varios trozos por otra cadena que actúa de delimitador.

Este fue uno de mis primeros códigos en C que hice para afianzar conocimientos de la sintaxis del lenguaje, así que no es muy legible que digamos, pero eso sí, funciona perfectamente.

En el código ya hay un ejemplo de cómo se usa.

Código: C

#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;
}

HOLA!!!

Esto me hace recordar a una funcion que arme en vb6 para eso mismo!

Dejo link por si alguien lo quiere


GRACIAS POR LEER!!!
"Algunos creen que soy un bot, puede que tengan razon"
"Como no se puede igualar a Dios, ya he decidido que hacer, ¡SUPERARLO!"
"La peor de las ignorancias es no saber corregirlas"

*Shadow Scouts Team*                                                No tienes permitido ver los links. Registrarse o Entrar a mi cuenta