How to concatenate two strings into C without using <string library. h>?

Asked

Viewed 107 times

0

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

int main(){
    
    char vet1[20] = "Bom ";
    char vet2[20] = "dia";
    
    for(int i=0; vet1[i]!='\0'; i++){
        for(int j=0; vet2[j]!='\0'; j++){
            vet1[i]=vet2[j];
            printf("%c%c", vet1[i], vet2[j]);
        }
    }
    
    return 0;
}
  • Hello John. Welcome to the site. In future questions it is important to add a [mcve] of the problem with a step by step of what you have already done and explain clearly and objectively what you need. To better enjoy the site, understand and avoid closures is worth reading the Stack Overflow Survival Guide in English. Thank you for understanding.

1 answer

1


So you have to figure out where the first position is array ends, and the first loop even does this, but then everything gets confused, because that’s just what you should do in it, should not have content, just navigate until you get to the end. Then use a variable to store it and it must survive the end of the initial loop.

Then you should start copying the contents of the second array for the first, starting in the position he found before. So this second loop for copy is completely independent of the first, except that the beginning of the first array comes from the result obtained in the first.

I did not consider it necessary to give backup if the copy exceeds the limit of the first vector, in a real case this would be necessary.

#include <stdio.h>

int main() {
    char vet1[20] = "Bom ";
    char vet2[20] = "dia";
    int i;
    for (i = 0; vet1[i] != '\0'; i++);
    for (int j = 0; vet2[j] != '\0'; j++) vet1[i++] = vet2[j];
    printf("%s", vet1);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You can do it with one loop, but it’s inefficient and confusing.

  • vlw until q gave helped I will try with a single loop

  • Now you can vote for everything on the site too.

Browser other questions tagged

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