Home Resource Centre C++ String Concatenation | All Methods Explained (With Examples)

Table of content:

C++ String Concatenation | All Methods Explained (With Examples)

The string is one of the most important topics in C++ programming language. In simple terms, a string is nothing but a collection of characters, and we use them for many purposes. For example, whenever we have to use an integer value that is out of bounds, we use a string to make it happen. In this article, we will discuss one of the most important operations on strings, i.e., C++ string concatenation. We'll discuss this string operation, how to perform concatenation and more.

Before we proceed, there are a few things one must note about strings. First, a string is very similar to an array, and we can traverse each character of a string just like array traversal. It should be noted that string in C++ is not a built-in data type but a custom one.

What Is String Concatenation In C++?

In simple terms, concatenation means linking things together in a series or merging things (here, input strings) together in a series. In other words, in C++, concatenation of strings means adding strings together to form another new/ single string.

Let's understand this with an example. Suppose we have two strings- one is “Being,” and the other is “Unstoppable,” and we want to concatenate them. Then the concatenated string will be “Being Unstoppable”

To learn all about the history and timeline of this language read- History Of C++ | Detailed Explanation (With Timeline Infographic)

How To Concatenate Two Strings In C++ Using The ‘+' Operator?

Now that we know what C++ string concatenation is and have seen an example, let's discuss the ways in which we can implement this in code. The first way that we will look at is- the concatenation of string using the ‘+’ operator.

Note that this is different from what we use in arithmetic operations. Because in arithmetic operations, the ‘+’ operator is used to add to numbers. But in the case of concatenation, the '+' operator is used to link two strings together. We have given two code snippets below; the first one of these shows the use of '+' as an arithmetic operator. And the second code snippet shows the use of the '+' operator for the concatenation of strings in C++.

Code example showing implementation of the '+' arithmetic operator:


          #include 

using namespace std;

int main()

{

int a=5,b=6;

cout <<a+b<<endl;

}
      

Output: 11

Explanation: The '+' operator is used to get the addition of two numbers, a and b. But in strings, it is totally different.

Example: “5” +”6” !=”11”

In strings, if we use the ‘+’ operator, then it will give us a new string made from the two strings that we are concatenating.

Code example showing implementation of the '+' operator for concatenation of strings:


          #include 

using namespace std;

int main()

{

string str1="Be";

string str2="Unstoppable";

cout <<"New String after concatenating: "<<str1+str2<<endl;

}
      

Output:

New String after concatenating: BeUnstoppable

Explanation: When we used the ‘+’ operator on strings str1 and str2, it gives us a new string, “BeUnstoppable”.

Check this out- Boosting Career Opportunities For Engineers Through E-School Competitions

String Concatenation Using The strcat( ) Function

In C++, there is an inbuilt method for concatenating the strings, which is the strcat() function. This might seem similar to the append() fn, but there are key differences we must know. For example, in the strcat() fn, the destination string must be a pointer to a character array containing a C++ string. This is because it works for C-style strings only, that is, character arrays (str[]=”Unstoppable”). It cannot be used on C++ strings (str=”Unstoppable”).

Code Example:


          #include <bits/stdc++.h>

using namespace std;

int main()

{

char str1[] = "You are ";

char str2[]= "Unstoppable";

strcat(str1, str2);

cout <<"New String after concatenating: "<<str1<<endl;

return 0;

}
      

Output:

New String after concatenating: You are Unstoppable

Explanation: In the above code, there are two strings of C type (character arrays), i.e., str1 and str2. We have passed these two strings into the strcat() function strcat(str1,str2), and it will give us a new string- You are Unstoppable

Note: The time complexity of the strcat() function is O(l1+l2), where l1 and l2 are the lengths of the strings.

Concatenation Of Two Strings In C++ Using Loops

For beginners and others who do not have an understanding of the strcat() function, another method for concatenating the strings is the use of a simple loop (like for loop or a while loop). In this section, we will discuss how to use both these types of loops to concatenate two strings in C++.

Also, note that we can both traverse strings and concatenate them with the use of loops.

1. C++ Program to Concatenate Two Strings Using The 'for Loop'

The below code shows us how to concatenate two strings using the for loop. In this case, we will be using two for loops to concatenate the two strings. The first for loop will be used for the traversal of the first string and store every character of it inside a third-string variable. Similarly, we will do this for the second string, and the resultant third string will be our concatenated string.

Example program C++:


          #include <bits/stdc++.h>

using namespace std;

int main()

{

// declaring string variables

string str1="Learn with ",

str2="Unstop";

string str3;







for ( int i = 0; i < str1.size(); i++)

{

// adding character of the str1 into str3




str3 = str3 + str1[i];

}




for ( int i = 0; i < str2.size(); i++)

{

// adding character of the str1 into str3




str3 = str3 + str2[i];

}




cout <<"New String after concatenating: "<<str3<<endl;

return 0;

}
      

Output:

New String after concatenating: Learn with Unstop

Explanation:

In the above example, we have taken two strings, str1 and str2, and another empty string str3. Using the first for loop, we added each character of str1 to str3, and using the second for loop, we added each character of str2 to str3, which is our final string.

Note- str1.size() function tells us the size of the string.

2. C++ Program to Concatenate Two Strings Using a while Loop

The code below shows us how to concatenate two strings using a while loop. To concatenate the two strings, we will be using two while loops. The first while loop will be used for the traversal of the first string and to get the first empty index. After that, we will use another while loop to add every character of the second string to the first string if it is not null. After adding the first string will get our result, i.e., a concatenated new string.

Example:


          #include <bits/stdc++.h>

using namespace std;

int main()

{

char str1[]="You are ", str2[]="Unstoppable";

int i=0, j=0;




while(str1[i] != '\0')

{

i++;

}




while(str2[j] != '\0')

{

str1[i] = str2[j];

i++;

j++;

}




str1[i] = '\0';

cout <<"New String after concatenating: "<<str1<<endl;

return 0;

}
      

Output:

New String after concatenating: Learn with Unstop

Explanation:

In the above code, we have used two loops for string concatenation, one for iterating the first string and for adding the character of the second string to the first string.

String Concatenation Using The append() Function

There is another inbuilt function in C++ to concatenate the two strings, i.e., the append function. Using the in-built append method, we can add a string to another string, and when we print the first string, we will get the concatenated string. Let's look at an implementation program to get a better understanding of how to use this function to concatenate strings in C++.

Example:


          #include <bits/stdc++.h>

using namespace std;

int main()

{

string str1="You are ", str2="Unstoppable";




str1.append(str2);

cout <<"New String after concatenating: "<<str1<<endl;

return 0;

}
      

Output:

New String after concatenating: Learn with Unstop

Explanation-: In the above program, we have taken two strings and concatenated them using the append() function. If we concatenated str1 to str2, then to get the final result, we must print str1 and vice versa.

C++ String Concatenation Using The Inheritance Of Class

Inheritance is the concept of object-oriented programming. It is a process in which a new class (derived class) is created from an existing class (base class). And we can use this inheritance feature to concatenate two strings in C++. Below is a code example to showcase how this can be done. 

Example:


          #include <bits/stdc++.h>

using namespace std;

class unstop

{

protected:

virtual string concatenate(string &str1, string &str2) = 0;

};

class unstoppble: protected unstop {

public:

string concatenate (string &str1, string &str2) {

string str3;

str3 = str1 + str2;

return str3;

}

};

int main()

{




string str1="You are "

, str2="Unstoppble";

unstoppble obj;

cout <<"New String after concatenating: " << obj.concatenate (str1, str2)<<endl;

return 0;

}
      

Output:

New String after concatenating: Learn with Unstop

Explanation-: In the above example, we have created one base class, ‘unstop’, which has a virtual function for concatenating the two strings. In the derived class ‘unstoppable’, we have taken a third variable str3, to store the concatenated string. When we create an object from a derived class in the main function, it gives us a concatenated string.

Concatenate Two Strings In C++ With The Friend and strcat() Functions

Apart from the methods we shared above, there are other ways to concatenate two strings in C++. This includes the use of the friend function and the strcat() function.

Example:


          #include <bits/stdc++.h>

using namespace std;

class unstop {

public:

char str1[100]="Your are ", str2[100]="unstoppable";

friend void myfun(unstop b);

};

void myfun (unstop obj)

{

strcat (obj.str1, obj.str2);

cout <<"New String after concatenating: " <<obj.str1;

}

int main()

{

unstop obj;

myfun(obj);

return 0;

}
      

Output:

New String after concatenating: Learn with Unstop

Explanation:

In the above example, ‘unstop’ is a class that represents a string of characters. The myfun function concatenates two string objects by using the strcat() function, which appends the characters of one string to the end of another string.

Why Do We Need To Concatenate Two Strings?

Concatenating strings is one of the most important operations in strings in many programming languages, including Java, Python, C++, and JavaScript. It is widely used for applications such as web development, data processing, and text analysis. But do you know why we need to conduct this operation? Well, below are some other reasons why we should concatenate strings:

  • Cross-Language Compatibility: String concatenation is a concept that is used in every programming language. It means if we understand it, we can apply this to any programming language. It is very useful when we working on a project which requires the use of two or more languages.
  • Efficient Memory Usage: String in any programming language cannot be altered after we create them. And if we modify or append the string, then a new string object will be created. Now, if it is done repeatedly, it will cause inefficient memory use. On the other hand, if we use string concatenation, we can create a new string by combining existing strings, which is much more memory-efficient.
  • Building Dynamic Strings: Concatenating strings allows us to create dynamic strings by combining different pieces of text or data at runtime.
  • Formatting Data: String concatenation is often used to format data for display or storage purposes. For example, when logging data or generating reports, we may need to concatenate different pieces of data together, such as dates, times, numbers, or other values, to create a formatted output.

Let's take a look at another simple example of C++ string concatenation:

Suppose we want to print the name of every person in a family. The surname of every person will be the same. Let's suppose the surname is “xyz”.

Note that if we use string concatenation, we don't have to type surname every time. 


          #include <bits/stdc++.h>

using namespace std;




int main()

{

string surname="xyz";

cout<<"Amit " + surname<<endl;

cout<<"Rohit " + surname<<endl;

cout<<"Hema " + surname<<endl;

cout<<"Shruti " + surname<<endl;

return 0;

}
      

Output:

Amit xyz
Rohit xyz
Hema xyz
Shruti xyz

Explanation: We can define only one variable for the surname and can use it multiple times.

How To Reverse Concatenation Of Strings In C++?

We have seen many ways to concatenate strings in C++. Now we will see how to reverse the concatenation of string. Reverse concatenation means if a string of multiple words is given, we print individually every word of it.

Example: “You are unstoppable”

You

are

unstoppable

There is an inbuilt function for reverse concatenation in C++ that is strtok() function. It should be noted that it only works for C-style strings.


          #include <bits/stdc++.h>

using namespace std;




int main ()

{

char str[] ="You are Unstoppable";

cout<<"String Before Reverse Concatenation: "<<str<<endl;

char * ptr;

ptr = strtok (str," ,.-");

cout<<"String After Reverse Concatenation: "<<endl;

while (ptr != NULL)

{

cout<<ptr<<endl;

ptr = strtok (NULL, " ,.-");

}

return 0;

}
      

Output:

String Before Reverse Concatenation: You are Unstoppable
String Before Reverse Concatenation:
You
are
Unstoppable

Explanation:

In the above code, we have taken a C-style string, and after using the strtok() function, the concatenated string will be broken into parts. While using the strtok() function, we have defined the character at which the string will break, that is, space(“ “), comma (,), full stop (.), and dash(-).

Conclusion

String concatenation is a very helpful tool in programming that allows us to efficiently manipulate strings, build dynamic strings, improve code readability and maintainability, achieve cross-language compatibility, and optimize performance. It is a fundamental concept that is widely used in various applications and programming languages. Understanding the benefits and proper usage of C++ string concatenation can greatly enhance our ability to work with strings and write efficient and effective code.

Frequently Asked Questions

Q. What is to_string in C++?

The to_string is an inbuilt function that is used to convert an integer value to a string value. For example-

int num=10;

// now value 10 will be a string.

string str= to_string(num);

Q. What is the fastest way to concatenate two strings?

There are many ways to concatenate strings in C++. But amongst all the methods available, the strcat() function is the fastest way to concatenate the strings. If we have passed two strings into the strcat function strcat(str1,str2) and it will give us a new string. The time complexity of the strcat() function is O(l1+l2), where l1 and l2 is the length of the strings.

Q. What operator is used to concatenate two strings?

In C++, the ‘+’ operator is used to concatenate two strings. In strings, if we use the ‘+’ operator, then it will give us a new string made from the two strings that we are concatenating.

“Be “ + “Unstoppable” = “Be Unstoppable”

Q. Can we concatenate two arrays in C++?

We cannot concatenate two arrays like strings, but there are other ways to merge the arrays. To merge the two arrays, we create another array and copy every element of the two arrays into the third array. The size of the third array should be equal to the sum of the size of two arrays that are getting merged.

The time complexity of this approach will be O(n1+n2), where n1 and n2 are the sizes of two arrays, and space complexity will also be O(n1+n2).

Q. How to concatenate two strings in C++ without using the strcat() function?

If we do not want to use the strcat() function for string concatenation, there are other methods. This includes the use of the append() function, using loops (for loop and while loop), and the ‘+’ operator and inheritance.

Q. How to split a string into 2 strings in C++?

If we want to split a string into strings into 2 strings, there is an inbuilt function for reverse concatenation in C++, which is the strtok() function. It should be noted that it only works for C-style strings. While using the strtok() function, we have defined the character at which the string will break, that is, space with quotes (“ “), comma (,), full stop (.), and dash(-).

You might also be in reading the following:

  1. Typedef In C++ | Syntax, Application & How To Use It (With Examples)
  2. Find In Strings C++ | Examples To Find Substrings, Character & More!
  3. String Compare In C++ | Learn To Compare Strings With Examples
  4. Difference Between C And C++| Features | Application & More!
  5. 10 Best C++ IDEs That Developers Mention The Most!
Shivani Goyal
Manager, Content

An economics graduate with a passion for storytelling, I thrive on crafting content that blends creativity with technical insight. At Unstop, I create in-depth, SEO-driven content that simplifies complex tech topics and covers a wide array of subjects, all designed to inform, engage, and inspire our readers. My goal is to empower others to truly #BeUnstoppable through content that resonates. When I’m not writing, you’ll find me immersed in art, food, or lost in a good book—constantly drawing inspiration from the world around me.

TAGS
Engineering Computer Science
Updated On: 16 May'23, 05:55 PM IST