String Concatenation in C++

by | C++, Programming, Tips

In this guide, we’ll explore various methods to concatenate strings in C++, from classic approaches to modern C++ techniques. Whether you’re working with std::string, string literals, or other string types, you’ll learn the most efficient ways to combine strings in your C++ programs.

📚 String Concatenation Quick Reference
std::string
The standard C++ string class that provides dynamic string handling capabilities, including various concatenation methods and memory management.
string_view
A non-owning reference to a string, introduced in C++17. Provides efficient read-only access without copying data, optimal for string operations.
append()
A member function of std::string that efficiently adds characters to the end of a string, with multiple overloads for different input types.
stringstream
A stream class that allows flexible concatenation of different data types into a string, providing automatic type conversion.
Capacity Management
Techniques like reserve() to pre-allocate string memory, preventing multiple reallocations during concatenation operations.
String Literals
Fixed strings embedded directly in the code (e.g., “Hello”). Can be concatenated at compile-time using the + operator.
Move Semantics
Modern C++ feature that allows efficient transfer of resources between strings, reducing unnecessary copying during concatenation.
SSO (Small String Optimization)
An optimization technique used by std::string where small strings are stored directly in the string object rather than being heap-allocated.

Using the + Operator

The simplest and most intuitive way to concatenate strings in C++ is using the + operator. This method is easy to read and works well for simple concatenations. The += operator provides a shorthand for appending to an existing string.

Basic String Concatenation Examples
#include <iostream>
#include <string>

int main() {
    // Basic variables
    std::string first = "Hello";
    std::string second = "World";
    std::string space = " ";

    // Method 1: Direct concatenation with +
    std::string result1 = first + " " + second;  // Concatenate with space
    std::cout << "Result 1: " << result1 << '\n';

    // Method 2: Using += for incremental addition
    std::string result2 = "Hello";
    result2 += space;    // Add space
    result2 += "World";  // Add second word
    std::cout << "Result 2: " << result2 << '\n';

    // Method 3: Mixing string literals and std::string
    std::string name = "C++";
    std::string result3 = "I love " + name + "!";  // Note: string literal must be added to std::string
    std::cout << "Result 3: " << result3 << '\n';

    // Method 4: Multiple concatenations
    std::string greeting = first + space + second + "!";
    std::cout << "Result 4: " << greeting << '\n';

    return 0;
}
Result 1: Hello World
Result 2: Hello World
Result 3: I love C++!
Result 4: Hello World!

Important Notes:

  • String literals (like "text") must be concatenated with a std::string, not with each other
  • Use += when adding to an existing string for better efficiency
  • The + operator creates a new string with each operation

Warning: While the + operator is convenient, it may not be the most efficient choice for multiple concatenations as it creates temporary string objects. For complex concatenations, consider using append() or string streams.

Using append() Method

The append() method provides more flexibility and can be more efficient than the + operator, especially when performing multiple concatenations. It offers several overloads for different use cases and allows for fine-grained control over the concatenation process.

Key Features of append()

  • In-place Modification: Directly modifies the string without creating temporary objects
  • Multiple Overloads: Supports various input types and partial string operations
  • Method Chaining: Returns a reference to the string for consecutive operations
  • Automatic Capacity Management: Handles memory reallocation efficiently
Using append() Method - Email Template Example
#include <iostream>
#include <string>

std::string createEmailTemplate(const std::string& userName,
                              const std::string& orderNumber,
                              const std::string& trackingCode) {
    // Estimate final size to avoid reallocations
    std::string email;
    email.reserve(200);  // Reserve space for typical email length

    // Build email template using different append methods
    email.append("Dear ");  // Basic append
    email.append(userName);
    email.append(",\n\n");

    // Append multi-line order confirmation
    email.append("Thank you for your order with FastShip Inc.\n")
         .append("Order details:\n")
         .append(50, '-')  // Append separator line
         .append("\n");

    // Append order information with specific formatting
    email.append("Order #: ");
    email.append(orderNumber);
    email.append("\n");

    // Append tracking information using substring
    std::string trackingInfo = "Your tracking code: " + trackingCode + " (save for reference)";
    email.append(trackingInfo, 0, trackingInfo.find("(") - 1);  // Exclude the parenthetical
    email.append("\n\n");

    // Append footer using character array with length
    const char* footer = "Best regards,\nThe FastShip Team";
    email.append(footer, strlen(footer));

    return email;
}

int main() {
    std::string email = createEmailTemplate("John Smith",
                                          "ORD-2024-123",
                                          "TRK789XYZ");

    std::cout << email << std::endl;
    std::cout << "\nTemplate Statistics:" << std::endl;
    std::cout << "Length: " << email.length() << std::endl;
    std::cout << "Capacity: " << email.capacity() << std::endl;

    return 0;
}
Dear John Smith,

Thank you for your order with FastShip Inc.
Order details:
--------------------------------------------------
Order #: ORD-2024-123
Your tracking code: TRK789XYZ

Best regards,
The FastShip Team

Template Statistics:
Length: 173
Capacity: 200

Common append() Overloads:

  • append(const string& str): Append entire string
  • append(const string& str, size_t pos, size_t len): Append substring
  • append(size_t n, char c): Append n copies of character
  • append(const char* s): Append C-style string
  • append(const char* s, size_t n): Append first n characters

Note: While append() is very flexible, consider using reserve() when you know the final string size to prevent multiple reallocations during repeated append operations.

Using String Streams

String streams provide a flexible way to concatenate different types of data without explicit conversions.

String Stream Example
#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::stringstream ss;

    // Concatenate different types
    std::string name = "John";
    int age = 30;
    double height = 1.75;

    ss << "Name: " << name << "\n"
       << "Age: " << age << "\n"
       << "Height: " << height << "m";

    std::string result = ss.str();
    std::cout << result << std::endl;

    return 0;
}
Name: John Age: 30 Height: 1.75m

Modern C++ Approaches

Modern C++ (C++17 and later) introduces several powerful features that make string concatenation more efficient and easier to manage. Key among these is std::string_view, which provides a non-owning reference to string data.

Understanding string_view

std::string_view offers several advantages for string operations:

  • Zero-Copy References: Provides a view into existing string data without copying
  • Improved Performance: Reduces memory allocations and copying operations
  • Compatible Interface: Works seamlessly with both std::string and string literals
  • Lightweight: Only stores a pointer and a length, making it very efficient to pass around
Modern C++ String Handling
#include <iostream>
#include <string>
#include <string_view>

void concatenateModern() {
    // Using string_view for efficient string references
    std::string_view prefix = "Hello";  // No copy, just a view
    std::string_view suffix = "World";  // No copy, just a view

    // Preallocate space for efficiency
    std::string result;
    result.reserve(prefix.length() + suffix.length() + 1);  // Prevent reallocations

    // Append using string_view
    result.append(prefix);  // Efficient append from view
    result.append(" ");     // Add space
    result.append(suffix);  // Efficient append from view

    std::cout << "Result: " << result << std::endl;
}

int main() {
    // Call the modern concatenation function
    concatenateModern();
    return 0;
}
Result: Hello World

Advanced Modern Techniques

Modern C++ provides several other features that can enhance string concatenation:

Advanced Modern C++ String Features
#include <iostream>
#include <string>
#include <string_view>

int main() {
    // 1. Using string literals with s suffix
    using namespace std::string_literals;
    auto str1 = "Modern"s + " C++"s;  // Direct string literal concatenation

    // 2. Using string_view with substr
    std::string_view full_text = "Hello, Modern World!";
    auto part = full_text.substr(7, 6);  // View into "Modern" portion

    // 3. Efficient multi-string concatenation
    std::string result;
    result.reserve(100);  // Pre-allocate capacity

    // Chain multiple append operations
    result.append("Building")
          .append(" ")
          .append("Modern")
          .append(" ")
          .append("Strings");

    std::cout << "String Literals: " << str1 << '\n'
              << "String View: " << part << '\n'
              << "Chained Result: " << result << std::endl;

    return 0;
}
String Literals: Modern C++
String View: Modern
Chained Result: Building Modern Strings

Best Practices for Modern String Concatenation:

  • Use string_view when you don't need to modify the string data
  • Always pre-allocate space using reserve() when final size is known
  • Consider using string literals with the s suffix for automatic type deduction
  • Use method chaining with append() for multiple concatenations
  • Take advantage of move semantics when working with temporary strings

Important: When using string_view, ensure the underlying string data remains valid for the lifetime of the view. A string_view doesn't own its data, so it becomes invalid if the original string is destroyed or modified.

Performance Considerations

Modern C++ techniques offer several performance benefits:

  • Reduced Copies: string_view eliminates unnecessary string copying
  • Efficient Memory Use: Pre-allocation prevents multiple reallocations
  • Move Semantics: Allows efficient transfer of string resources
  • Compile-Time Optimizations: String literal operations can be optimized at compile time

Modern Features Availability: These features require at least C++17 for string_view and C++14 for string literals. Ensure your compiler supports these features and appropriate flags are enabled (e.g., -std=c++17).

Performance Considerations

  • Use += or append()instead of + for multiple concatenations
  • Preallocate string capacity using reserve() when final size is known
  • Consider string_view for read-only string references
  • Use string streams when mixing string data with other types

Best Practices

  • Avoid creating temporary string objects when possible
  • Use appropriate method based on your use case (concatenation vs. formatting)
  • Consider string_view for improved performance with string literals
  • Preallocate memory when final string size is known

Conclusion

We've explored various methods for string concatenation in C++, from basic operators to modern techniques. Each approach has its use cases:

  • Use + operator for simple, one-off concatenations
  • Use append() or += for multiple concatenations
  • Use string streams for mixing different types
  • Use modern C++ features like string_view for better performance

Choose the method that best fits your specific needs while considering performance implications.

Congratulations on reading to the end of this tutorial! We hope you now have a better understanding of string concatenation in C++ and its various approaches. For further exploration of string manipulation in C++ and related documentation, check out the resources in our Further Reading section.

Have fun and happy coding!

Further Reading

Attribution and Citation

If you found this guide and tools helpful, feel free to link back to this page or cite it in your work!

Profile Picture
Senior Advisor, Data Science | [email protected] |  + posts

Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.

Buy Me a Coffee ✨