Beginners Programs :

C Program To Concatenate Two Strings | 4 Simple Ways

C program to concatenate two strings – In this article, we will brief in on the multiple ways to concatenate two things in C programming.

Suitable examples and sample programs have also been added so that you can understand the whole thing very clearly. The compiler has also been added with which you can execute it yourself.

The ways used in this piece are as follows:

  • Using Standard Method
  • Using Function
  • Using Recursion
  • Using String Library Function

A string is nothing but an array of characters. The value of a string is determined by the terminating character. Its value is considered to be 0.

C program to concatenate two strings

As it is evident with the image uploaded above, we need to enter both the strings which we need to concatenate or link.

Both the strings that have been entered are as follows:

string1: hello

string2: world

Linking both the strings will get the new string to be:

helloworld

Thus, the multiple ways to do so in C programming are as follows:

Using Standard Method

  1. We are combining the two strings into one string.

2) Read the entered two strings using gets() function as gets(s1) and gets(s2).

3) Get the length of the string s1 using string library function strlen(s1) and initialize to j.

4) The for loop iterates with the structure for(i=0;s2[i]!=’\0′;i++) ,

append the characters of string s2 at s1[i+j] of the string s1 until there is no character is available in the string s2. Here we are adding the string s2 at the end of the string s1.

5) Print the concatenated string s1.

Output:

Using Function

  1. The main() calls the stringconcatenate() function to combine the two strings.

2) The function gets the string s1 length using strlen(s1).

3) Append the character of string s2[i] at s1[i+j].Repeat this step by increasing i value until no character available in s2. Here, we append the characters of string s2 to s1 from the end of s1.

4) After all iterations of for loop, we will get concatenated string s1.

5) The main() prints the string s1.

Output:

Using Recursion

  1. The function stringconcatenate() gets the string length of s1.

a) If no elements are available in s2 then assign s2 with a null character.

b) Otherwise, add the element of the string s2 at the end of the string s1 as s1[i+j]=s2[i]and increase the i value.

c) The function calls itself by passing modified string s1,s2 as arguments. It calls recursively until no elements are available in s2.

2)The main() prints the concatenated string s1.

Output:
Using String Library Function
  1. The strcat(s1,s2) is a string library function available at the header file “string.h”.

2) The function strcat(s1,s2) combines the string s2 with s1.

Output: