Concatenate char of an array in C

3

I have a char pointer with numbers , which would be: puntero = [1,2,4,5,\n,2,3,\n,5,2,1];

How can I make the following?:

nuevo = [1245,\n,23,\n,521]; , \n is a line break, it's just to represent it.

I have tried doing a cycle with strcat and strtol , but it does not give results.

    
asked by chantaman1 23.10.2016 в 21:53
source

2 answers

2

You have not put code so I'm going to make assumptions.

When you say you have a Char arrangement with numbers I understand that you have this:

char numeros[] ={'1','2','4','5','\n','2','3','\n','5','2','1'};

And what you want to achieve is this:

char **resultado = {"12345","23","521"};

In the first case you have loose characters. Each character is individual and is not related to any other. However, in the second case you have three strings of characters.

If you have studied character strings you will know that the strings must end with a null character.

Applying this you can solve the problem in three comfortable steps:

  • Copy your size array N to another size N + 1 .
  • In the N position of the new array you write a null character.
  • You scroll through the new array and replace the line breaks with null characters.

Said with a code could look like this:

char numeros[11] ={'1','2','4','5','\n','2','3','\n','5','2','1'};
char resultado[12];
resultado[11]='
printf("%s\n",resultado);
for(int i=0;i<11;i++)
{
  if(resultado[i]=='
char numeros[] ={'1','2','4','5','\n','2','3','\n','5','2','1'};
') printf("%s\n",&resultado[i+1]); }
'; memcpy(resultado,numeros,11); for(int i=0;i<12;i++) { if(resultado[i]=='\n') resultado[i]='
char **resultado = {"12345","23","521"};
'; }

To print the strings it is enough to locate the null characters ... After each null character there is the start of one of the searched strings:

char numeros[11] ={'1','2','4','5','\n','2','3','\n','5','2','1'};
char resultado[12];
resultado[11]='
printf("%s\n",resultado);
for(int i=0;i<11;i++)
{
  if(resultado[i]=='%pre%')
    printf("%s\n",&resultado[i+1]);
}
'; memcpy(resultado,numeros,11); for(int i=0;i<12;i++) { if(resultado[i]=='\n') resultado[i]='%pre%'; }

If you work with dynamic memory the thing changes slightly, but as you do not give more details ...

Greetings

    
answered by 23.10.2016 / 23:11
source
0

I hope this helps you:

    char puntero[] = {'1','2','4','5'}; // Tu arreglo
    char nuevo[500][50]; // Tu nuevo arreglo de strings
    char str[500]; // Auxiliar para concatenar los caracteres
    int i;
    for (i = 0; i < 4; i++) // Concateno los caracteres
        str[i] = puntero[i];

    strcpy(nuevo[0], str); // Lo agrego al arreglo nuevo
    printf("%s\n", nuevo[0]); // Probamos que haya salido bien

Obviously you will have to adapt it to your program with the corresponding cycles and algorithms to cut in the '\ n', etc. This is just demonstrative.

Greetings!

    
answered by 23.10.2016 в 23:11