C join

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

[ Hits: 5.524 ]

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

Download joinsplit.tar.gz

Download join.tar (versão 2)




Função que junta um array char** em apenas uma string, todos os elementos separados por um token.


join( {"Enzo", "Ferber"}, ':');  // só demostração!

Retorna: "Enzo:Ferber:"

;)

O arquivo que estou enviando tem o split.c e o join.c

Pra compilar,

$ gcc -c split.c
$ gcc -c join.c
$ gcc -c joinsplit.c
$ gcc -o joinsplit joinsplit.o split.o join.o
$ ./joinsplit Viva o Linux :

:)

  



Versões atualizadas deste script

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

Changelog: Script menor e melhor.

Agora trabalha com input do stdin, o que o torna facilmente utilizável com pipes na linha de comando.

$ echo $LS_COLORS | split | join

É exatamente igual a

$ echo $LS_COLORS

Sendo o 'split' o meu script, que também será atualizado.

Download join.tar


Esconder código-fonte

/* join.c
 *
 * Enzo Ferber
 * dez 2011
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

char *join ( char **elements, char n )
{
   register int i;
   int length = 0;
   char *all;
   char **s = elements, *a, *b; // references

   /* what length the whole string should have
    * +1 for each separator
    */
   while ( *s ) length += ( strlen( *(s++) ) + 1 );

   /* memory
    * +1 for the null terminating char 
    */
   all = (char *) malloc ( (length + 1) * sizeof(char));

   // error check
   if ( !all )
   {
      printf ( "# Error in malloc()\n");
      return NULL;
   }

   // new reference
   s = elements;

   // whole joined string
   b = all;
   
   /* 
    * @a = each element
    */
   while ( (a = *s++) )
   {
      /* 
       * copy the element into the joined string
       * @a - each character of the element
       */
      while ( *a ) *b++ = *a++;

      // end of each elements, a separating character
      *b++ = n;
   }

   // null-termination character
   *b = 0x0;

   // return the string
   return all;
}

Scripts recomendados

Simulador do Sorteio da Mega Sena

Fila dinâmica em C

Máquina virtual

Jogo da Velha contra o Computador.

Pequeno Shell Unix em C++


  

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