In this tutorial you will learn about the C++ Program to Concatenate Two Strings and its application with practical example.
C++ Program to Concatenate Two Strings
In this tutorial, we will learn to create a C++ program that will Concatenate Two Strings in C++ programming.
Prerequisites
Before starting with this tutorial we assume that you are best aware of the following C++ programming topics:
- Operators in C++ Programming.
- Basic Input and Output function in C++ Programming.
- Basic C++ programming.
- Using Strings in C++ Programming.
Algorithm:-
1 2 3 4 5 6 7 8 9 |
1. Declaring the variables for the program. 2. Taking input string 1 and 2 from the user. 3. Concatinating the string from the taken variable. 4. Printing the result string. 5. End |
Program to Concatenate Two Strings
Concatenation means to join two values i.e. Strings. In strings, only one variable is declared which can store a sentence. It’s a collection of characters, digits, and Special characters. First will take the input string one from the user. Then we will take a second-string from the user and now we will concatenate that two stings.
Using the below program example.
Program Code:-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <iostream> using namespace std; int main () { //declaring the variables for the program string str1, str2, result; // declaring the string variables int i; //declaring the integer variables //taking input string1 from the user cout <<" Enter the first string: "; cin >> str1; // take string1 //taking input string2 from the user cout << " Enter the second string: "; cin >> str2; // take second string // use for loop to enter the characters of the str1 into result string for ( i = 0; i < str1.size(); i++) { result = result + str1[i]; // add character of the str1 into result } // use for loop to enter the characters of the str2 into result string for ( i = 0; i < str2.size(); i++) { result = result + str2[i]; // add character of the str2 into result } cout << " The Concatenation of the string " << str1 << " and " << str2 << " is " <<result; return 0; } |
Output:-
In the above program, we have first initialized the required variable.
![](https://www.w3adda.com/wp-content/uploads/2021/06/1-v-4.jpg)
- str1 = it will hold the string value.
- str2 = it will hold the string value.
- result = it will hold the string value.
- i = it will hold the integer value.
Taking Input string from the user for copying the string.
Concatenating the strings taken from the user with the help of the for loop.
Printing the output Concatenated String.