EnzoFerber
(usa FreeBSD)
Enviado em 20/12/2011 - 18:06h
split.c
/* 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), last = 0;
int elements = 0, elpos = 0;
char **array;
/* number of new itens in array */
for ( i = 0; i < len; i++ ) if ( str[i] == n ) elements++;
if ( str[len - 1] != 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 || str[j] == '{TTEXTO}')
{
/*
* @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;
}
array [ elements ] = NULL;
/* return array */
return array;
}
/* EoF */
test.c
#include <stdio.h>
#include <stdlib.h>
extern char **split ( char *, char, int *);
int main ( int argc, char *argv[] )
{
int n, i;
char **s;
if ( argc > 2 )
{
s = split ( argv[1], argv[2][0], &n );
while ( *s ) printf ( "# %s\n", *(s++ ));
}
return 0;
}
$ gcc -c split.c
$ gcc -c test.c
$ gcc test.o split.o -o test
$ ./test enzo:ferber :
# enzo
# ferber
$
Acho que agora até no Windows vai imprimir. Coloquei um elemento NULO no fim do ponteiro de retorno de split.
Tem algumas mudanças, agora que você descobre de boa ai quais são... 3 coisas a mais só ;)
[]'s