You can concatenate strings using the + operator. You can concatenate more than one strings.
Syntax:
string data = string1 + string2;
Example:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "Friends!";
// Print the string
cout << str1 + " " + str2 << "\n";
return 0;
}
Explanation:
str1 and str2 are added with blank empty string.
Output:
Hello, Friends!
Example2:
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "Friends!";
string str3 = str1 + " "+str2;
// Print the string
cout << str3 << "\n";
return 0;
}
In the above example, str1 and str2 are added and put into str3 variable.
Output:
Hello, Friends!
C++ Concatenate Strings – Interview Questions
Q 1: What is string concatenation?
Ans: Joining two or more strings.
Q 2: Which operator is used?
Ans: +
Q 3: Can append() be used?
Ans: Yes.
Q 4: Can C-style strings be concatenated?
Ans: Yes, using strcat().
Q 5: Is concatenation memory efficient?
Ans: It may allocate new memory.
C++ Concatenate Strings – Objective Questions (MCQs)
Q1. Which operator is used to concatenate two strings in C++?
Q2. What will be the output of the following code?
string a = "Hello ";
string b = "World";
cout << a + b;
Q3. Which function can also be used to concatenate two strings?
Q4. What is the output of this code?
string a = "Good";
a.append(" Morning");
cout << a;
Q5. Which statement about string concatenation is TRUE?