c
  1. c-program-to-concatenate-two-strings

Program to Concatenate Two Strings - (C Programs)

In this tutorial, we'll discuss how to write a program in C to concatenate two strings. Concatenating strings means combining two or more strings into a single string.

Syntax

The syntax for concatenating two strings in C is as follows:

#include <stdio.h>
#include <string.h>
 
void main()
{
   char string1[] = "hello ";
   char string2[] = "world";
   char result[20];
   
   strcpy(result, string1);
   strcat(result, string2);
   
   printf("Concatenated string using strcat(): %s\n", result);
}

Example

Suppose you have the strings "hello" and "world", and you want to concatenate them into a single string "hello world". You can use the following code to do so:

#include <stdio.h>
#include <string.h>
 
void main()
{
   char string1[] = "hello ";
   char string2[] = "world";
   char result[20];
   
   strcpy(result, string1);
   strcat(result, string2);
   
   printf("Concatenated string using strcat(): %s\n", result);
}

Output

The output of the above code would be:

Concatenated string using strcat(): hello world

Explanation

The above C program uses the strcpy() and strcat() functions to concatenate two strings into a single string. The strcpy() function copies the contents of one string to another, while the strcat() function appends one string to the end of another.

Use

Concatenating two or more strings is a common task in programming and is especially useful in applications that involve string manipulation. This code can be used in various applications where we need to combine multiple strings into a single string.

Summary

In this tutorial, we discussed how to write a program in C to concatenate two strings using the strcpy() and strcat() functions. We covered the syntax, example, output, explanation, use, and importance of concatenating strings in programming. By using these functions correctly, you can easily combine multiple strings into a single string in your C programs.

Published on: