Algorithm


1. Declare two string variables, str1 and str2.

2. Input the first string (str1).

3. Input the second string (str2).

4. Concatenate str1 and str2, storing the result in a new string variable (result).

5. Display the concatenated string (result).

6. End.

Code Examples

#1 Code Example- Concatenate String Objects

Code - C++ Programming

#include <iostream>
using namespace std;

int main()
{
    string s1, s2, result;

    cout << "Enter string s1: ";
    getline (cin, s1);

    cout << "Enter string s2: ";
    getline (cin, s2);

    result = s1 + s2;

    cout << "Resultant String = "<< result;

    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter string s1: C++ Programming
Enter string s2: is awesome.
Resultant String = C++ Programming is awesome.

#2 Code Example- Concatenate C-style Strings

Code - C++ Programming

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char s1[50], s2[50];

    cout << "Enter string s1: ";
    cin.getline(s1, 50);

    cout << "Enter string s2: ";
    cin.getline(s2, 50);

    strcat(s1, s2); 

    cout << "s1 = " << s1 << endl;
    cout << "s2 = " << s2;

    return 0;
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
Enter string s1: I love
Enter string s2: C++ programming
s1 = I love C++ programming
s2 = C++ programming
Advertisements

Demonstration


C++ Programing Example to Concatenate Two Strings-DevsEnv