In C++, strings are represented using the string class. This class provides many useful methods to manipulate strings, including concatenation.
In this tutorial, we’ll learn how to concatenate two strings using C++.
Concatenation means joining two or more strings together to form a new string.
In C++, we can concatenate two strings using the ‘+’ operator or the append method of the string class.
Here’s how to concatenate two strings using the ‘+’ operator:
#include <iostream> #include <string> using namespace std; int main() { string str1 = "Hello"; string str2 = "world"; string result = str1 + " " + str2; cout << result << endl; return 0; }
In this example, we first declare two strings, str1 and str2, and initialize them with the values “Hello” and “world”, respectively.
We then concatenate the two strings using the ‘+’ operator and store the result in a new string variable result. Finally, we print the result to the console using cout.
Here’s how to concatenate two strings using the append method:
#include <iostream> #include <string> using namespace std; int main() { string str1 = "Hello"; string str2 = "world"; string result = str1; result.append(" "); result.append(str2); cout << result << endl; return 0; }
In this example, we first declare two strings, str1 and str2, and initialize them with the values “Hello” and “world”, respectively.
We then declare a new string variable result and initialize it with the value of str1. We then use the append method to append a space and the value of str2 to result. Finally, we print the result to the console using cout.
In conclusion, concatenating two strings in C++ is a simple task that can be accomplished using the ‘+’ operator or the append method of the string class.