Manipulating std::string Objects

Concatenate Strings in C++

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 125 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved