String Concatenation in C++
Concatenation is the process of joining two or more strings end-to-end. In C++, you can use the +
operator or the append()
function for concatenation.
Using the +
Operator
Example: Concatenating Strings with +
#include <iostream>
#include <string>
int main() {
std::string firstName = "Karthick";
std::string lastName = "AG";
std::string fullName = firstName + " " + lastName;
std::cout << "Full Name: " << fullName << std::endl;
return 0;
}
Output:
Full Name: Karthick AG
Using the append()
Function
Example: Concatenating Strings with append()
#include <iostream>
#include <string>
int main() {
std::string greeting = "Vanakkam";
greeting.append(", World!");
std::cout << greeting << std::endl;
return 0;
}
Output:
Vanakkam, World!
Key Takeaways
- You can concatenate strings using the
+
operator or theappend()
function. - Concatenation combines strings into a single string.
- Ensure proper spacing when concatenating strings.