String Concatenation in C++

String Concatenation in C++

There are many ways to concatenate strings 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: 

Cpp

Output:

String example

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. In C++, string concatenation 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. In C++, it can be seen that common uses for concatenation may include building messages, paths, and formatted output.

Why is String Concatenation Necessary? 

String concatenation is important because it safely allows you to construct meaningful text out of shorter pieces of information. For example, you can then join 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.

Example: 

Cpp

Output: 

 string concatenation

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 concatenation string in the string result. Using cout, the concatenated string is displayed on your console. 

Methods to Concatenate the String

A few methods are used to concatenate the strings in C++:

1. Using String append()

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.

Example: 

Cpp

Output:

Using String append() concatenation

The above program 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”. 

2. Using strcat()

The strcat() method is a C-style function for sorting character arrays, also called C-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: 

Cpp

Output: 

Using strcat()

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. Using a for Loop

In C++, strings can be concatenated 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: 

Cpp

Output: 

Using a for Loop

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. Using 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.

Example: 

Cpp

Output: 

Using stringstream

Usage of stringstream helps join 2 strings, 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

String concatenation 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: 

Cpp

Output: 

Using Friend Function with OOP

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. Using Friend Function with 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: 

Cpp

Output: 

Using Friend Function with OOP

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 concatenate() is called to concatenate their strings and print the output. 

String Concatenation with Arrays in C++

In C++, string concatenation 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 Concatenation

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: 

Cpp

Output: 

Using memcpy() for Efficient Concatenation

This C++ code illustrates string concatenation 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 Concatenation

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 concatenation mechanism, 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:

Cpp

Output: 

Using sprintf() for Concatenation

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 using std::vector<char> in C++ 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.

Example:

Cpp

Output:

This code shows the string concatenation 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 of doing this when it comes to efficiency and safety in handling strings in applications.

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++.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner