How to Concatenate Two Strings in C++
In C++, you can concatenate two strings using the "+" operator or the "append" function. This allows you to combine two or more strings into a single string.
Syntax
Using the "+" operator:
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2;
Using the "append" function:
string str1 = "Hello";
string str2 = "World";
str1.append(" ");
str1.append(str2);
string result = str1;
Example
#include <iostream>
#include <string>
using namespace std;
int main() {
string str1 = "Hello";
string str2 = "World";
string result = str1 + " " + str2;
cout << result << endl;
return 0;
}
Output
Hello World
Explanation
In the above example, we have two strings "str1" and "str2" containing the words "Hello" and "World" respectively. We concatenate these strings using the "+" operator to create a new string called "result". The resulting string is then printed to the console using the "cout" statement.
Use
String concatenation is commonly used when you need to combine two or more strings into a single string. This can be useful when you need to build a longer message or concatenate variables into a single output string.
Important Points
- String concatenation is the process of combining two or more strings into a single string.
- The "+" operator and "append" function can be used for concatenation.
- The resulting string is a new string containing the concatenated values.
- The original strings are not modified by the concatenation process.
Summary
In summary, concatenating two or more strings in C++ is a relatively simple process. You can use either the "+" operator or the "append" function to combine two or more strings into a single string. The resulting string is a new string that contains the concatenated values, and the original strings are not modified by the process.