C++ String Concatenation
String concatenation means joining two or more strings together. In C++, you can concatenate strings using the std::string class or C-style character arrays.
1. Using + Operator (std::string)
The + operator is the easiest way to concatenate std::string objects.
#include <iostream>
#include <string>
using namespace std;
int main() {
string firstName = "John";
string lastName = "Doe";
string fullName = firstName + " " + lastName;
cout << "Full Name: " << fullName;
return 0;
}
2. Using append() Function
The append() function adds text to the end of a string.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "Hello";
str.append(" World");
cout << str;
return 0;
}
3. Using strcat() (C-Style Strings)
For C-style strings, the strcat() function from
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str1[20] = "Hello";
char str2[] = " World";
strcat(str1, str2);
cout << str1;
return 0;
}
4. Important Notes
1. The + operator works only with std::string objects. 2. append() modifies the original string. 3. For C-style strings, always allocate sufficient memory before using strcat(). 4. Prefer std::string for safer and easier string manipulation.
Conclusion
C++ provides multiple ways to concatenate strings. The std::string class offers the safest and most convenient approach, while C-style string concatenation requires careful memory management.
Codecrown