Concatenate String into C without using strcat() function

Asked

Viewed 4,296 times

0

need a help, needed to solve this programming language exercise, would concatenate a string, in case STRING_B in STIRNG_A, without use of ready function, by pointer method.

example:

ENTRADAS >> "CASA " - "BAHIA"

SAIDA >> CASA BAHIA

follows the code...

#include <stdio.h>
#include <string.h>
/*escreva uma funcao em c que recebe a referencia de duas strings e concatena
a segunda na primeira sem usar funcao strcat()*/

void ptr(char *string_a, char *string_b)
{
    int i;
    do{
        string_a++;
    }while(*string_a!='\0');
    do{
        string_a=*string_b;
        string_b++; 
    }while(*string_b!='\0');
}
int main (void)
{
    char string_a[250];
    char string_b[250];
    puts(" -- DIGITE UMA PALAVRA -- ");
    gets(string_a);
    puts(" -- DIGITE UMA PALAVRA -- ");
    gets(string_b);
    ptr(string_a,string_b);
    puts(string_a);
    return 0;
}

1 answer

1


There’s no reason to use the do_while and then increment, if the was made for it, your code is a little confusing for me, I did it in a slightly simpler way:

char* ptr(char *string_a, char *string_b)
{
    int i;
   for(i=0; string_a[i]!='\0'; ++i); //Percorre toda a string_a, para saber o tamanho da mesma
   for(int j=0; string_b[j]!='\0'; ++j, ++i) //Percorre toda a string_b, para concatena-la
   {
      string_a[i]=string_b[j];
   }
    string_a[i]='\0';
    return string_a;
}
int main (void)
{
    char string_a[250];
    char string_b[250];
    puts(" -- DIGITE UMA PALAVRA -- ");
    gets(string_a);
    puts(" -- DIGITE UMA PALAVRA -- ");
    gets(string_b);
    puts(ptr(string_a,string_b));
    return 0;
}

See working on Ideone.

Com while:

char* ptr(char *string_a, char *string_b)
{
    int i = 0, j = 0;
    while(string_a[i]!='\0') { ++i; }
    while(string_b[j]!='\0') 
    {
        string_a[i]=string_b[j];
        j++; i++;
    }
    string_a[i]='\0';
    return string_a;
}

See working on Ideone.

  • Error] 'for' loop initial declarations are only allowed in C99 or C11 mode; submitted this error!

  • @Agenaro I do not know why the error, but so do with while even, I edited my answer.

  • @Francisso Now it worked ! Thanks. only in the code you sent last missed Point and comma after '++i'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.