Last active
May 5, 2017 04:21
-
-
Save Florencia-97/6a00969d50ce5074b8d268bc4031de3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <string.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
/* | |
* Devuelve en un arreglo dinámico terminado en NULL con todos los subsegmentos | |
* de ‘str’ separados por el carácter ‘sep’. Tanto el arreglo devuelto como las | |
* cadenas que contiene son allocadas dinámicamente. | |
* | |
* Quien llama a la función toma responsabilidad de la memoria dinámica del | |
* arreglo devuelto. La función devuelve NULL si falló alguna llamada a | |
* malloc(), o si ‘sep’ es '\0'. | |
*/ | |
int cant_parametro(const char* str, char sep){ | |
int pos=0; | |
int contador=0; | |
while( str[pos]!='\0'){ | |
if(str[pos]==sep)contador++; | |
pos++; | |
} | |
return contador; | |
} | |
//devuelve la cantidad de bytes que hay hasta el primer separador dado | |
int cant(const char *str, char sep){ | |
int i=0; | |
while(str[i]!= sep && str[i]!='\0'){ | |
i++; | |
} | |
return i; | |
} | |
char** split (const char* str, char sep){ | |
if(sep=='\0') return NULL; | |
int tam_arreglo=cant_parametro(str,sep)+1; | |
char** arreglo_aux= malloc(sizeof(char*)*(tam_arreglo+1)); | |
if(arreglo_aux==NULL)return NULL; | |
const char* puntero = str; | |
for(int i=0;i<tam_arreglo;i++){ | |
int bytes = cant(puntero,sep); | |
char* cadena = malloc(sizeof(char)*(bytes+1)); | |
memcpy(cadena,puntero,bytes); | |
cadena[bytes]='\0'; | |
arreglo_aux[i]=cadena; | |
puntero+=(bytes+1); | |
} | |
arreglo_aux[tam_arreglo]=NULL; | |
return arreglo_aux; | |
} | |
int main(void){ | |
char* cadena = malloc(sizeof(char)*(11)); | |
cadena[0]='\0'; | |
const char* arreglo= "abc,def,gh"; | |
strcat(cadena,arreglo); | |
char separador=','; | |
char** nuevo_arreglo=split(cadena,separador); | |
for (int i=0;i<3;i++){ | |
printf("%s\n",nuevo_arreglo[i]); | |
} | |
for(int i=0;i<3;i++){ | |
free(nuevo_arreglo[i]); | |
} | |
free(nuevo_arreglo); | |
free(cadena); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment