Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to concatenate two string

C++ Code Example — String Programs

ADVERTISEMENT

WAP to concatenate two string

Objective

Write a C++ program to concatenate two strings together.

Algorithm / Approach

  1. Declare three strings: s1, s2, and s3.
  2. Read inputs for both s1 and s2.
  3. Use the addition operator to join them: s3 = s1 + s2.
  4. Print the concatenated string.
main.cpp
#include<iostream>
using namespace std;
int main() {
 string s1,s2,s3;
 cout<<"Enter 1st string : ";
 getline(cin,s1);
 cout<<"Enter 2nd string : ";
 getline(cin,s2);
 s3 = s1+s2;
 cout<<"Concatenate String : "<< s3;
 return 0;
}

Expected Output

Enter 1st string : c++
Enter 2nd string : is awesome
Concatenate String : c++ is awesome

Explanation of the Program

  • Concatenation is the process of appending one string to the very end of another.
  • Just like the assignment operator, the addition operator (+) is overloaded for the string class. It takes the contents of the right string and mathematically appends it to the end of the left string.

Complexity

Time Complexity O(n + m) - Where n and m are the lengths of the two strings.
Space Complexity O(n + m)
ADVERTISEMENT