Concatenating two std::string
objects in C++ is straightforward and can be done using the +
operator or the append()
method. Here’s how you can do it:
+
OperatorThe simplest way to concatenate two strings is by using the +
operator. This creates a new string by combining the contents of two strings.
#include <iostream>
#include <string>
int main() {
std::string FirstName{"John"};
std::string LastName{"Doe"};
std::string FullName
= FirstName + " " + LastName;
std::cout << FullName;
}
John Doe
append()
MethodAlternatively, you can use the append()
method to concatenate strings. This method modifies the original string.
#include <iostream>
#include <string>
int main() {
std::string Greeting{"Hello"};
std::string Name{"Alice"};
Greeting.append(" ").append(Name);
std::cout << Greeting;
}
Hello Alice
+=
OperatorYou can also use the +=
operator to append a string to an existing string:
#include <iostream>
#include <string>
int main(){
std::string Greeting{"Hello"};
std::string Name{"Alice"};
Greeting += " " + Name;
std::cout << Greeting;
}
Hello Alice
+
operator creates a new string, which can be less efficient than append()
if used repeatedly in a loop.+
can make the code more readable and concise.By using these methods, you can easily concatenate std::string
objects in C++, depending on your specific needs and performance considerations.
Answers to questions are automatically generated and may not have been reviewed.
std::string
ObjectsA practical guide covering the most useful methods and operators for working with std::string
objects and their memory