Concatenate Strings in C++

How can I concatenate two std::string objects in C++?

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:

Using the + Operator

The 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

Using the append() Method

Alternatively, 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

Using += Operator

You 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

Considerations

  • Performance: The + operator creates a new string, which can be less efficient than append() if used repeatedly in a loop.
  • Readability: Using + 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.

Manipulating std::string Objects

A practical guide covering the most useful methods and operators for working with std::string objects and their memory

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

The append() Method vs += Operator
What is the difference between append() and += operator for strings in C++?
Insert Substring in C++
How can I insert a substring into a specific position within a std::string?
Replace Substring in C++
How can I replace a substring within a std::string with another string?
Iterate over String
How can I iterate through each character of a std::string using a range-based for loop?
Reserve vs Resize
What is the difference between reserve() and resize() methods in std::string?
Convert to wstring
How can I convert a std::string to a std::wstring?
Count Character Occurrences
How can I count the number of occurrences of a character in a std::string?
Restrict String Length
How can I ensure a std::string does not exceed a specific length?
Reverse String
How can I reverse the contents of a std::string?
Trim Whitespace
How can I trim whitespace from the beginning and end of a std::string?
Compare String vs Vector
What are the differences between std::string and std::vector?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant