EnzoFerber
(usa FreeBSD)
Enviado em 20/12/2011 - 12:31h
/* split.c
*
* Enzo Ferber
* dez 2011
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/* poscpy()
*
* @t = target string (should be malloc(a + b + 1))
* @s = source string
* @a = startpoint in source string (must be > 0 )
* @b = endpoint in source string (must be < strlen(s))
*
* @function
* copys s[a] -> s[b] into t.
*
*/
void poscpy ( char *t, char *s, int a, int b )
{
while ( a < b ) *(t++) = *(s + (a++));
*t = 0x0;
}
char **split ( char *str, char n, int *length )
{
register int i, j, a;
/* control */
int len = strlen(str);
int elements = 0, elpos = 0;
char **array;
/* number of new itens in array */
for ( i = 0; i < len; i++ ) if ( str[i] == n ) elements++;
/* get the memory */
array = ( char ** ) calloc ( elements , sizeof(char *));
if ( !array )
{
printf ( "# Error in malloc(*).\n" );
return NULL;
}
/* the number of elements for the caller */
*length = elements;
/* lvl1
*
* @i = will be the start point for copy
*/
for ( i = 0; i < len; i++ )
/* lvl2
*
* @j = will be end point for copy
*/
for ( j = i; j <=len; j++ )
/* found splitChar or EoL */
if ( str[j] == n )
{
/*
* @i has start point
* @j has end point
*/
array[ elpos ] = ( char *) malloc ( (j - i + 1) * sizeof(char));
if ( !array[ elpos ] )
{
printf ( "# lvl2\n");
printf ( " # Error in malloc().\n" );
return NULL;
}
/* copy the string into the array */
poscpy ( array[ elpos ], str, i, j );
/* increment array position */
elpos++;
/* after the copy is done,
*
* @i must be equal to @j
*/
i = j;
/* end loop lvl2 */
break;
}
/* return array */
return array;
}
int main ( void )
{
int len, i;
char *str = "Enzo:de:Brito:Ferber:Viva:O:Linux:A:Maior:Comunidade:Linux:da:America:Latina!:";
char **elements = split(str, ':', &len);
// reference pointer
char **a = elements;
printf ( "# Elements: %d\n", len );
while ( *a ) printf (" # %s\n", *(a++));
return 0;
}
Enzo Ferber
[]'s