There are many ways for String Concatenation in C++. From the classic + operator string manipulation to C-style strings and stringstream, each impacts the performance and readability of your code. How do you know, out of so many methods, that you’re choosing the right one?
In this article, we are going to cover the best techniques for string concatenation in C++ and will tell you which ones can provide optimal performance for your code.
Table of Contents:
What is a String in C++?
The std::string class from the <string> header defines strings in C++ or can be constructed using C-like character arrays (C-strings). String objects are better and safer to use than arrays because their memory management is automatic and comes with many built-in functions. For instance, string operations such as concatenation, comparison, extraction of a substring, and searching can easily be done using std::string, without worrying about buffer overflows or null termination. Moreover, std::string is part and parcel of the C++ standard library, making it as portable and efficient as it possibly could be for most applications.
Example:
Output:
The above C++ program is to illustrate both the definition and use of a string with the standard string class. The program includes <string>, which allows the string functionality, and a string variable, str, is initialized with “Intellipaat”. The string is printed to the console with cout, giving the following output: Intellipaat.
String Concatenation in C++
Joining two or more strings into a single string is called string concatenation. The string concatenation in C++ can be done simply with the + operator with std::string or by using the append() function, which adds the strings effectively. The order of operands maintains the concatenation, that is, str1 + str2 is different from str2 + str1. It should also be kept in mind that at least one of the concatenating strings should be a std::string object to avoid mismatch errors while combining with C-style strings. It can be seen that common uses to join strings in C++ may include building messages, paths, and formatted output.
Why Do You Need String Concatenation in C++?
String concatenation in C++ is important because it safely allows you to construct meaningful text out of shorter pieces of information. For example, you can then join strings in C++ like joining the first and last names of the user to display their full name and build file paths by combining directory names with filenames, as well as constructing personalized messages out of user input or variable values. It also improves the readability, flexibility, and usability of code in real-world applications where textual data gets combined and displayed frequently.
Using +
Operator to Concatenate Strings
In C++, using the ‘+’ Operator is a straightforward and common method for combining textual data, especially when constructing meaningful messages or paths from smaller pieces of information.
Example:
Output:
In the above code, s1 takes the string as “Intellipaat”, and s2 takes the string “paat”. Now, by using +, we are concatenating the two strings and storing the concatenated string in the string result. Using cout, the concatenated string is displayed on your console.
6 Best Methods for String Concatenation in C++ (With Examples)
Here are the 6 best methods for string concatenation in C++ with examples:
1. Using append() Function in C++ for String Concatenation
The append function of the std::string class adds the second string at the end of the first, modifying the original string. In that case, it works almost the same as the + operator, but can be a bit more efficient in certain cases. The function is overloaded to append the other string, a C-style string, a substring, or a specific number of characters. Such a case is of the event creating larger strings in parts, particularly in performance-sensitive applications. This is a common method for C++ string append.
Example:
Output:
The above program shows string concatenation in C++, which takes two strings, s1, s2, and assigns the strings “Intelli” and “paat” to s1 and s2. The function append() is used to add the strings, resulting in “Intellipaat”. And, thus, this program shows a practical use of C++ string append.
2. Concatenating C-Style Strings in C++ Using strcat()
The strcat() method is a C-style function for sorting character arrays, also called C-style strings. The second character array is appended to the first one here. This function is defined in <cstring> and operates on null-terminated character arrays only. It very much differs from the C++ string object in that strcat() assumes that the destination array has enough space to store the resultant concatenation; otherwise, it leads to undefined behavior.
Example:
Output:
The program defines two character arrays, s1 and s2, where it is ensured that s1 has enough space to contain the combined result. Then the strcat() function appends the content of s2 to the end of s1, thus modifying s1. Finally, the result “Intellipaat” is printed to cout.
3. Manual String Concatenation in C++ Using a for Loop
String concatenation in C++ can also be done manually, character by character, copying them from one string to another with the help of a for loop. This is particularly useful when one is working with C-style character arrays and memory and copying are explicitly controlled. Though it is more error-prone than built-in functions such as strcat() or std::string’s + operator, it provides a clear view into how these things work under the hood with string operations.
Example:
Output:
In this C++ example, two C-style strings, s1 and s2, are concatenated using a for loop. First, you have to navigate to the end of the first string, s1, by iterating over its characters until the null character . Then you loop through each character of s2, copying it to s1 beginning at the end of s1. Finally, we append the null terminator at the end of the combined string so that it is properly terminated before we print it.
Get 100% Hike!
Master Most in Demand Skills Now!
4. Concatenating Strings in C++ with stringstream
stringstream enables string concatenation in C++ by treating strings as streams. It could easily allow an append of strings or data types together more flexibly and effectively than through the + operator or any other method. This makes C++ stringstream concatenate a powerful method for complex formatting.
Example:
Output:
Usage of the C++ stringstream concatenate method helps to join strings in C++ program. The strings are s1 and s2. Here, just concatenate all strings into the stringstream object ss using the << operator. Finally, through this process, the joined strings are retrieved with ss.str() and printed on the console.
5. Using Inheritance in C++ for Custom String Concatenation
String concatenation in C++ can also be performed through inheritance, by creating a class extending an existing string class, such as std::string, and adding the concat functionality as a member function.
Example:
Output:
In the code here, the Derived class inherits from the Base class, containing a string variable text1. The Derived class adds another string variable, text2, and the function show() concatenates and prints text1 and text2.
6. Concatenating Strings in C++ Using Friend Functions and OOP
According to object-oriented programming (OOP), a friend function is one that is not a member of the class but is able to access the private and protected data members of the class. Friend functions are useful for granting direct access to the private state of a class to certain functions or other classes without making them members of the class.
Example:
Output:
In this program, a class named MyString is defined with a private member called str to store a string. A friend function named concatenate() is used to access these private members from any two MyString objects and concatenate them. The main function creates two objects, a and b, and the concatenate() is called to concatenate their strings and print the output.
Difference Between strcat and append in C++
Here we have discussed the difference between strcat and append in C++.
Feature |
strcat (C-style string) |
append (C++ std::string) |
Type |
Function from the C standard library (<cstring>) |
Method of the std::string class |
Header Required |
<cstring> |
<string> |
Input Type |
C-style null-terminated char arrays |
C++ std::string objects |
Safety |
Unsafe (no bounds checking) |
Safe (automatically manages memory) |
Return Type |
char* (pointer to destination string) |
std::string& (reference to modified string) |
Null Terminator |
Requires null-terminated strings |
Managed internally by std::string |
Memory Handling |
The user must ensure the destination buffer is large enough |
Automatically resizes as needed |
Example Usage |
strcat(dest, src); |
str1.append(str2); |
Risk of Buffer Overflow |
High |
Low |
Modern C++ Recommendation |
Avoid in favor of safer alternatives |
Recommended |
String Concatenation with Arrays in C++
String concatenation in C++ for arrays mostly constitutes C-style strings (known as character arrays), and here, strings are concatenated either manually by way of function calls or utilizing a loop. Different methods of concatenating C-style strings (character arrays) in C++ are described below.
1. Using memcpy() for Efficient String Concatenation in C++
Another method of concatenating arrays is memcpy() from the C standard library. This method is more efficient than copying the characters manually using a loop.
Example:
Output:
This code illustrates string concatenation in C++ by memcpy(). Calculating the length of s1 and s2 with strlen(), memcpy() subsequently copies S2’s contents into S1, right after where the preexisting content stops, thus ensuring the null terminator gets copied by copying len2 + 1 characters. Therefore, the expected result is “Hello, ” plus “Intellipaat!” equals “Hello, Intellipaat!”.
2. Using sprintf() for String Concatenation in C++
A function known as sprintf() in C++ can combine strings in an array with a fixed character size while writing formatted outputs. The use of this function provides an efficient string concatenation in C++, but it also requires careful memory management to avoid buffer overflow, thus proving to be less safe than dynamic string manipulations, such as using std::string.
Example:
Output:
In this program, sprintf is used to merge string s2 (“Intellipaat”) with string s1 (“Hello, “). The function strlen(s1) finds the current length of s1, and sprintf will append s2 from this length onward. The outcome is that s1 now holds the value “Hello, Intellipaat”, which is then subsequently printed.
String Concatenation Using std::vector<char>
String concatenation in C++ using std::vector<char> involves treating each string as a collection of characters stored in a vector. The individual characters from different strings are added to the vector, which automatically handles memory management as the vector size grows. Once all characters are concatenated into the vector, you can convert it back to a string using std::string for further processing or display. This method is another way to achieve a C++ string append operation efficiently.
Example:
Output:
This code shows the string concatenation in C++ through an std::vector<char>. Initially, it composes the characters of two strings (s1 and s2) into a std::vector<char>. Thereafter, the vector is converted back into a string, and the result is printed out, thus affecting the concatenation of both strings.
Conclusion
String concatenation in C++ is very basic, which simply means any number of strings can be combined into one string. C++ provides quite a few ways to achieve that, and they are the + operator, append(), strcat() for C-style strings, stringstream, and std::vector<char>. Each of these has some usage and performance considerations. An understanding of such techniques makes it possible for a developer to choose what is the most appropriate way for efficient string concatenation in C++.
String Concatenation in C++ – FAQs
Q1. Can we concatenate strings using the + operator in C++?
Yes, the operator + is generally used for making any combination whatsoever of std::string objects.
Q2. Is strcat() safe to use for C-style strings?
No, strcat() is in fact unsafe if the destination array is of inadequate size; it leads to potential buffer overflows.
Q3. How do you concatenate a string and an integer in C++?
You could convert the integer using to_string() and append it to the string.
Q4. Can we concatenate strings inside a loop efficiently?
Yes, but repeated concatenations in the loop would cause memory reallocations, which may lead to performance degradation.
Q5. What is the most efficient method to join multiple strings in C++?
Using a stringstream is the best method to concatenate many strings in C++.
Q6. What is the difference between strcat and append in C++?
strcat is a C function that concatenates C-style strings without bounds checking, while append is a C++ std::string method that safely appends strings with automatic memory management.
Q7. What is the difference between append() and + operator in C++?
append() modifies an existing string in-place; + creates a new concatenated string in C++.
Q8. Is strcat() better than append in C++?
No, std::string::append() is generally better and safer than strcat() in C++ because strcat() works with C-style character arrays and can lead to buffer overflows.