Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What are Strings?
2.1.
Defining a String
2.2.
Example 1
2.3.
C++
2.3.1.
Output
2.4.
Example 2
2.5.
C++
2.5.1.
Output
3.
What is C++ String Concatenation?
4.
Methods of Concatenate String
4.1.
1. Using the '+' Operator
4.1.1.
Example
4.2.
C++
4.2.1.
Output
4.2.2.
Complexity
4.3.
2. Using Append Function
4.3.1.
Example
4.4.
C++
4.4.1.
Output
4.4.2.
Complexity
4.5.
3. Using Strcat Function 
4.5.1.
Example
4.6.
C++
4.6.1.
Output
4.6.2.
Complexity
4.7.
4. Using a C++ for loop
4.7.1.
Example
4.8.
C++
4.8.1.
Output
4.8.2.
Complexity
4.9.
5. Using inheritance
4.9.1.
Example
4.10.
C++
4.10.1.
Output
4.10.2.
Complexity
4.11.
6. Using the friend function and strcat() function
4.11.1.
Example
4.12.
C++
4.12.1.
Output
4.12.2.
Complexity
5.
Frequently Asked Questions 
5.1.
What is string concatenation?
5.2.
How to concatenate string in C ++? 
5.3.
What are the different ways to perform string concatenation?
5.4.
Why is the '+' operator not preferred for C++ string concatenation?
5.5.
What does << do in string concatenation?
6.
Conclusion
Last Updated: Apr 4, 2024
Easy

C++ String Concatenation

Author Ayushi Goyal
0 upvote
gp-icon
Basics of C++
Free guided path
9 chapters
99+ problems
gp-badge
Earn badges and level up

Introduction

In C++ programming, string manipulation is like playing with building blocks, and string concatenation is one of the fundamental blocks. It's simply the process of merging two or more strings into one. While it might seem straightforward, understanding how to concatenate strings efficiently can significantly enhance your coding skills and open up a world of possibilities in your projects.

c++ string concatenation

So, let's start with the topic, starting with an introduction to what strings are.

What are Strings?

Strings refer to the sequence of characters. It is a useful datatype and is implemented in almost every programming language. In C++, strings are a part of a standard string class, i.e., std::string. This class stores strings in contiguous memory locations as a collection of bytes. Strings are handy when the user has to work with the input text. Various operations, like reverse, traverse, argument passing, concatenation, etc., can be performed on a string in C++

what are strings

As we now understand strings briefly, let's discuss how to define strings in C++. 

Defining a String

Before performing C++ string concatenation, we must know how to define a string. Defining a string in C++ is very simple. We have to use the 'string' keyword followed by an identifier(the name given to the string) and a semi-colon. We can also define a string and assign a value to them simultaneously. 

You can also check out Reverse A String In C

Example 1

  • C++

C++

#include<iostream>
using namespace std;

int main()
{
   string s = "Coding Ninjas";
   cout<<"Our defined string is : "<<s;
   return 0;
}
Output

output for string

The second way is by using a character array. This character array is also known as C-strings. It is a collection of characters stored in the form of an array. We don't need to use all the allocated space. Let's understand it by an example.

Example 2

  • C++

C++

#include<iostream>
using namespace std;

int main()
{
   char s[50] = "Character Array";
   cout<<"String is : "<<s;
  
   return 0;
}

In this, we declared a character array of size 50 but assigned only 15 characters. 

Output

output for character array

The third way is by using the 'getline' function. It is a pre-defined method in C++ to input a string from the user. This method requires an input stream and a string object as parameters. Let's see an example of defining a string using this method to understand it better. 

You practice by yourself with the help of online c++ compiler.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

What is C++ String Concatenation?

Combining two or more strings into one single resultant string is called C++ string concatenation. This can be achieved using various methods like the '+' operator, append() function, strcat() function, loops, inheritance, and friend functions. Each method offers different ways to join strings based on specific requirements, making it a versatile operation in string manipulation.

C++ String Concatenation

Methods of Concatenate String

There are 6 methods to Concatenate String:

  1. Using ‘+’ Operator.
  2. Using append( ) Function.
  3. Using strcat( ) Function.
  4. Using C++ for Loop.
  5. Using Inheritance.
  6. Using the Friend Function and strcat() Function.

Let's discuss each of these methods.

1. Using the '+' Operator

The simplest way to perform C++ string concatenation is using the '+' operator. It is just like adding two numbers and storing the result in a third variable. The '+' operator adds two strings into one in the given order and returns the resulting concatenated string. 

Example

  • C++

C++

#include<iostream>
using namespace std;

int main()
{
   // Define three strings
   string string1, string2, result;
  
   // Take input from the user
   cout<<"Enter string 1 - ";
   getline(cin, string1);
  
   cout<<"Enter string 2 - ";
   getline(cin, string2);
  
   // Store concatenated string in the third string
   result = string1 + string2;
  
   // Print the resultant string
   cout <<"Resultant String : " <<result;
  
   return 0;
}

Output

Output of String Concatenation in C++ Using the '+' Operator

Complexity

The space complexity of O(N). While the time complexity for C++ string concatenation using the '+' operator is O(N^2) where N = sum of lengths of string one and string two. But how!!!!

So, while performing this operation, in each iteration, a new string is created, and the previous string + new character is copied to it. 

So the sequence will be as follows: 

iteration1 + iteration2 + iteration3 + .... so on. And the number of characters added in each iteration will be: 1 + 2 + 3 + 4 + .... + N

This gives the sum of ‘N’ natural numbers; if you remember, the formula for this is = N*(N+1) / 2 

So complexity = O( N*(N+1) / 2 ) = O( (N^2 + N)/2 ) = O( N^2 )

Hence we can conclude that performing concatenation operations using the '+' operator proves costly, especially if strings are long. And therefore, there are alternative methods. So, Let's discuss performing C++ string concatenation using the 'append' function. 

Read More - Time Complexity of Sorting Algorithms

2. Using Append Function

The 'append' function adds the second string to the end of the first string. The syntax of this function is string1.append(string2). 

Example

  • C++

C++

#include<iostream>
using namespace std;

int main()
{
   // Define two strings
   string string1, string2;
  
   // Take input from the user
   cout<<"Enter string 1 - ";
   getline(cin, string1);
  
   cout<<"Enter string 2 - ";
   getline(cin, string2);
  
   // Call append function
   string1.append(string2);
  
   // Print the resultant string
   cout <<"String after append function : " <<string1;
  
   return 0;
}

Output

Output of String Concatenation in C++ Using Append Function

Complexity

The space complexity is O(N), where N = sum of lengths of both strings. While the time complexity for performing string concatenation using the append function is O(B), B = length of the second string. 

Unlike the '+' operator, the append function does not create a new string every time. It will add characters of the second string to the first string one by one in each iteration. So the number of iterations will be equal to the length of the second string. Thus the time complexity = O(number of iterations) = O(B). 

3. Using Strcat Function 

The strcat’ function concatenates string two to string one and ends the resulting string with a null character. It takes two arguments - ‘destination’ string and ‘source’ string. 

Source string = the string which is to be added. 

Destination string = the string in which the source string is added. 

This function returns the pointer to the destination string. Also, we need to include ‘string.h’ library to use strcat function. 

Example

  • C++

C++

#include<iostream>
#include<string.h>
using namespace std;

int main()
{
   // Define two strings
   char destination[50] = "Starting To ";
   char source[50] = "Ending";
  
   // Call strcat function
   strcat(destination, source);
  
   // Print the resultant string
   cout <<"Concatenated String : \n";
   cout <<destination;
  
   return 0;
}

Output

 Output of String Concatenation in C++ Using Strcat Function

Complexity

The space complexity = O(A+B) = O(N), 

where, 

A = length of the destination string

B = length of the source string

N = A+B. 

The time complexity is O(B), where ‘B’ is the length of the source string. 

4. Using a C++ for loop

To concatenate strings using a C++ for loop, we can iterate over the characters of the first string and append them to the second string. The following code shows an example:

Example

  • C++

C++

#include <bits/stdc++.h>

using namespace std;

int main() {
string str1 = "India ! ";
string str2 = " Namaste ";

// Concatenate the two strings using a for loop
for (int i = 0; i < str1.length(); i++) {
str2+=str1[i];
}

// Print the concatenated string
cout << str2 << endl;

return 0;
}

Output

 Output of String Concatenation in C++ Using for loop

Complexity

The time complexity of concatenating strings using a for loop is O(N), where N is the length of the first string. This is because we need to iterate over all of the characters of the first string in order to append them to the second string.

5. Using inheritance

To concatenate strings using inheritance, we can create a base class that contains a string variable. Then, we can create derived classes that inherit from the base class and add their own functionality. The following code shows a base class and a derived class that can be used to concatenate strings:

Example

  • C++

C++

#include <iostream>
using namespace std;

class String {
public:
string str;

String() {
str = "";
}

String(string str) {
this->str = str;
}
};

class ConcatenatedString : public String {
public:
ConcatenatedString(string str1, string str2) {
this->str = str1 + str2;
}
};

int main() {
string str1 = "Hello";
string str2 = "World!";

// Concatenate the two strings using the ConcatenatedString class
ConcatenatedString concatenatedString(str1, str2);

// Print the concatenated string
cout << concatenatedString.str << endl;

return 0;
}

Output

 Output of String Concatenation in C++ Using for inheritance

Complexity

The time complexity of concatenating strings using inheritance is O(N), where N is the length of the first string. This is because the ConcatenatedString class simply calls the + operator to concatenate the two strings.

6. Using the friend function and strcat() function

The strcat() function is a library function that can be used to concatenate strings. The strcat() function takes two strings as arguments and appends the second string to the end of the first string. The following code shows an example of how to use the strcat() function to concatenate strings:

Example

  • C++

C++

#include <iostream>
#include <cstring>

class MyString {
private:
char str[100]; // Assuming a maximum length

public:
MyString(const char* s) {
strcpy(str, s);
}

friend MyString operator+(const MyString& s1, const MyString& s2) {
MyString result("");
strcat(result.str, s1.str);
strcat(result.str, s2.str);
return result;
}

const char* toCStr() const {
return str;
}
};

int main() {
MyString str1("Hello, ");
MyString str2("world!");

MyString result = str1 + str2;

// Print the concatenated string
std::cout << result.toCStr() << std::endl;

return 0;
}

The above code defines a MyString class holding C-style strings and a toCStr() method. A friend operator+ combines MyString objects using strcat(). In the main function, we create instances, concatenate with +, and print the result using toCStr(). Complexities are O(N) time and O(1) space.

Output

  Output of String Concatenation in C++ using friend function and strcat() function

The strcat() function is a C function, so it is important to declare the str1 and str2 variables as C-strings before calling the function.

Complexity

The code defines a MyString class holding C-style strings and a toCStr() method. A friend operator+ combines MyString objects using strcat(). In the main function, we create instances, concatenate with +, and print the result using toCStr(). Complexities are O(N) time and O(1) space.

This is all about C++ string concatenation; let's now discuss some frequently asked questions related to this topic. 

Frequently Asked Questions 

What is string concatenation?

Combining two or more strings into one single resultant string is called C++ string concatenation.

How to concatenate string in C ++? 

In C++, you can concatenate strings using the + operator or the append() method for std::string objects. For C-style strings (char arrays), you can use functions like strcat() from the <cstring> library.

What are the different ways to perform string concatenation?

C++ provides three ways to perform this operation. These are by using the '+' operator, ‘append’ and ‘strcat’ functions.  

Why is the '+' operator not preferred for C++ string concatenation?

The time complexity for concatenation using + operator is O(N^2), which is inefficient, especially for long strings. Hence it is not advised to perform concatenation using + operator. 

What does << do in string concatenation?

In C++, the << operator is used for string concatenation when working with output streams such as cout. It appends the content on its right-hand side to the content already present on the left-hand side.

Conclusion

So, in this blog, we discussed the C++ string concatenation. Starting with an introduction to strings and ways to define them, followed by a discussion of concatenation methods, examples, and complexity. We hope that now you have a clear understanding of the topic and are ready to give it an attempt yourself!

If you found this one interesting, explore our other related blogs as well:

Do check out The Interview guide for Product Based Companies as well as some of the Popular interview problems from top tech companies like Amazon, Adobe, Google, Uber, Microsoft, etc.

Refer to our guided paths on Coding Ninjas Studio to learn more about Competitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses and refer to the mock test and problems available; take a look at the interview experiences and interview bundle for placement preparations.

Happy Coding!

Previous article
StringStream in C++
Next article
Abstraction
Guided path
Free
gridgp-icon
Basics of C++
9 chapters
104+ Problems
gp-badge
Earn badges and level up
Live masterclass