C++ String Concatenation

In C++, string concatenation refers to the process of joining two or more strings together to form a single string. There are several ways to concatenate strings in C++, some of the most commonly used methods are discussed below.

Using the ‘+’ operator

The ‘+’ operator is used to concatenate two strings. The following is an example:

string str1 = "Hello, ";
string str2 = "World!";
string str3 = str1 + str2;
cout << str3 << endl; // Output: Hello, World!

Using the ‘append’ function

The ‘append’ function can be used to append one string to another. The following is an example:

string str1 = "Hello, ";
string str2 = "World!";
str1.append(str2);
cout << str1 << endl; // Output: Hello, World!

Using the ‘+= operator

The ‘+=’ operator can be used to append one string to another. The following is an example:

string str1 = "Hello, ";
string str2 = "World!";
str1 += str2;
cout << str1 << endl; // Output: Hello, World!

Using the ‘push_back’ function

The ‘push_back’ function can be used to add a single character to the end of a string. The following is an example:

string str = "Hello, ";
str.push_back('W');
str.push_back('o');
str.push_back('r');
str.push_back('l');
str.push_back('d');
str.push_back('!');
cout << str << endl; // Output: Hello, World!

Conclusion

In C++, string concatenation can be done using several methods such as ‘+’ operator, ‘append’ function, ‘+=’ operator, and ‘push_back’ function. The choice of method depends on the requirement and the type of strings you are working with. It is important to note that these methods can be used to concatenate strings in different ways, and the final result will be a single string.

Leave a Reply

Your email address will not be published. Required fields are marked *