Concatenate Two Strings in C++

Last Updated On Tuesday 26th Apr 2022

concatenation of strings

You can concatenate two string objects

  • C++ concatenate (+) operator
  • C++ append() function
  • The strcat() method

C++ concatenate (+) operator

  • The + operator can be used between strings to add them together and returns a new string.

Syntax

	s1 + s2;
	

concatenating string

	#include <iostream>
using namespace std;

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

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

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

    result = s1 + s2;

    cout << "Final String = "<< result;

    return 0;
}
	

Output

	Enter String 1: Hello
Enter String 2: World
Final String = HelloWorld
	

concatenated string

The strcat() method

  • It is one of built-in method.
  • The strcat() method is used to concatenate strings in C++.
  • It takes char array as input and then concatenates the input values passed to the function.

adding strings

Syntax

	strcat(char *array1, char *array2)
	
	#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char s1[] = "Hello";
    char s2[] = " World";

    strcat(s1, s2);

    cout << s1 << endl;

    return 0;
}
	

Output

	Hello World
	

concatenation string

C++ append() function

  • It is also build-in method append() to concatenate strings.
  • The append() method can be used to add strings together.

Syntax

	s1.append(s2);
	

concatenate string

	#include <iostream>
using namespace std;

int main() {
    string s1 = "Hello";
    string s2 = " World";

    s1.append(s2);

    cout << s1 << endl;

    return 0;
}
	

Output

	Hello World