How to Concat Two String without Using strcat library function in C?

You can take Two String using either:

  char *str1 = "Kapil";

  char *str2 = "Thakar";


  char str1[] = "Kapil";

  char str2[] = "Thakar";

Now to concat these two string you need to create another string or you can use the same string. Here I have taken a new string to hold the combined string.

We don't the size of the new concat string, Concat string should have string length bigger than a sum of the string of string 1 & string 2. So we can either take

char str3[20]; //Here 20 is bigger than sum of string 1 & string 2.

char *str3 = (char *) malloc (length);
where length is sum of both string 1 & string 2.

Here you can not use

char str3[length] as you need to know the array size at compile time. So If you do like that then it will give you an error.

If we don't do this, then it will result in the segmentation fault. So It is required.

We can now copy the each character from string 1 & then we start copying text from string 2.

At the end, we need to add the null character to terminate the string properly. Else garbage character will be printed on the screen till it will find the null character.

#include "stdafx.h"

#include <conio.h>
#include "stdlib.h"
#include "stdio.h"
#include "string.h"

int main()


    char *str1 = "Kapil";

    char *str2 = "Thakar";
    int length = (strlen(str1)+strlen(str2));
    char *str3 = (char *) malloc (length);
    int i = 0;
    for(i=0; i<length; i++)
        if(i < strlen(str1))
            *(str3+i) = *(str1+i);
            *(str3+i) = *(str2+ (i - strlen(str1)));
    *(str3+i) = '\0';

    printf("\n%d,%s", length,str3);


    return 0;

For any Query please feel free to comment. 

Related Post:

Removing Space from Given String & Different Methods to Count Number of Ones in Given Value

Booting Sequence for Boot Process in Linux

How to count number of 1 or set bits in a given number

What is Segmentation fault?

How to Access Private Data Members in C++ without using friend function

Process Vs Thread 

How to Add Two Numbers Without Using + Operator in C 

Overview of Function Pointer in C with Example - What is function pointer & how to use it

How to Fork child process with waitpid & execl in linux with c example code

Share on Google Plus

About Unknown

"I am Kapil Thakar, an Embedded Engineer cum Blogger wants to learn new things. I love to share my knowledge solutions to the problems. Interested in Blogging, Creative-Writing, SEO, Website Creation, Video Making, Editing, Affiliation Programs, Online Making Money."
    Blogger Comment
    Facebook Comment


Post a Comment

Related Posts Plugin for WordPress, Blogger...