C split

Publicado por Enzo de Brito Ferber (última atualização em 23/01/2013)

[ Hits: 5.814 ]

Homepage: http://www.maximasonorizacao.com.br

Download 5274.split.c

Download split.tar (versão 2)

Download 1358166997.split.tar (versão 3)




Função parecida com a split() do JavaScript.

$ gcc -o split split.c
$ ./split


Pode-se excluir a função main desse fonte, e usá-lo como "include" em outros projetos:

$ gcc -c split.c
$ gcc split.o meu_programa.o -o meu_programa


No 'meu_programa' basta chamar a função.

  



Versões atualizadas deste script

Versão 2 - Enviado por Enzo de Brito Ferber em 21/12/2012

Changelog: Script menor e melhor.

Atualização para trabalhar com pipes na linha de comando.

Um exemplo muito bom de como pode ser usado é:

$ echo $LS_COLORS | split

Irá mostrar uma extensão por linha das definições de cores do 'ls'.

O programa agora aceita apenas 1 argumento (opcional), e o primeiro caractere desse argumento é o separador.

O default é ':' (o join também).

Download split.tar


Versão 3 - Enviado por Enzo de Brito Ferber em 14/01/2013

Changelog: Função menor, mais clara e melhor.

O programa agora lê da entrada padrão, stdin, o que faz a integração com a linha de comando do linux(pipes) muito boa.

Download 1358166997.split.tar


Esconder código-fonte

/* 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;
}

Scripts recomendados

Biller

Comando strncat

Teoria do Caos - (Equação Logística)

Conjunto de Mandelbrot (Fractal)

Saneago ncurses


  

Comentários

Nenhum comentário foi encontrado.


Contribuir com comentário




Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts