c++ string concatenation - c++ strings - concat c++ - concat strings - concatenate c++ - string concatenation

Using Concat on C++ Strings

Strings are a foundational tool in C++, just as in most programming languages. In fact, one of the first skills you’ll need to learn when picking up C++ is how to work with strings. In this article, we’ll explore how to join two or more C++ strings together through a process called concatenation.

Concatenation in C++

Before we look at specific methods for joining strings together, let’s get acquainted with “concatenation.” In programming languages, concatenating means generating a new object — usually a string — out of two or more original objects. It’s a key method to know when working with data objects, which themselves are C++ building blocks that every C++ developer must know.

So what does concatenation’s end result look like? Let’s look at an example. Say we have someone’s name and title:

string name = "Jane Doe";
string title = "Professor";

We want to merge the two strings using concatenation. The result will look something like this: 

string properName = "Professor Jane Doe";

It’s as simple as that! Now that we have an understanding of what C++ string objects look like post-concatenation, let’s dive into how specifically we would achieve this result. 

The + Operator

Employing the + operator is the most straightforward way to merge two or more strings into a single object. The + operator simply takes the C++ strings and adjoins them, returning a concatenated string object independent of the original two strings. Let’s take our previous example of Professor Jane Doe. In the examples that’ll follow, keep in mind that when we use string, we’ll be referring to the  std::string class, an instantiation of the basic_string class template. For that reason, we include <iostream> and std at the beginning of each program:

#include <iostream>
using namespace std;

int main() {
  string name = "Jane Doe";
  string title = "Professor";
  string properName = title + " " + name;

  cout << properName;
  return 0;
}

We get Professor Jane Doe written to the console. You’ll notice we included a space between the two variables — this is recommended over adding a space to the end or beginning of a string.The following approach to concat C++ strings with the + operator achieves the same result, but the added spaces within the input strings are inconsistent and messy:

string properName = "Professor " + "Jane" + " Doe";

It’s better to store your input strings in variables and add stand-alone spaces when necessary.

Using the + operator is great when you have more than two strings to concatenate or want a simple approach. Now let’s look at another in-built way to concat C++ strings.

Appending to C++ Strings

We can also use the in-built append() method to concat strings in C++. At face value, this method adds additional characters — the input to the append() method — to the string the method is called on. We can keep our program from the + operator and replace properName with the following line: 

string properName = title.append(name);

The output to this is ProfessorJane Doe. Notice that here, we do not have a space between “Professor” and “Jane”. In order to get the proper spacing, we have options besides adding a space at the end of our title string. The advantage to using append() is that you have many options when it comes to parameters and manipulating your added string. We can simply chain the append() method to achieve our desired result:

string properName = title.append(1u,' ').append(name);

This outputs Professor Jane Doe as we’d expect! Now let’s look at a full program we can run with added arguments to append(). Here, we include substrings and parameter options outlined in the C++ documentation for this method:

#include <iostream>
using namespace std;

int main ()
{
  string str;
  string name = "Professor Jane Doe";
  string verb = "teaches";
  string subjects1 = "math, programming";
  string subjects2 = "writing and also debate.";

  str.append(name).append(" ");                             // "Professor Jane Doe "
  str.append(verb).append(" ");                             // "teaches "
  str.append(subjects1, 6).append(", ");                    // "programming, "
  str.append("biology as well", 7).append(", ");            // "biology, "
  str.append(subjects1, 0, 4);                              // "math"
  str.append(3u,'.');                                       // "..."
  str.append(subjects2.begin()+8, subjects2.end());         // "and also debate."
 
  std::cout << str << '\n';
  return 0;
}

Although you can start by appending to name and not use str at all, we began the output string with an empty string str to show that you don’t always need a value when you begin concatenating. 

As you can see, you have a lot of options when using append(), so you might choose it over the + operator when you need to go more in-depth with string manipulation. Now, let’s look at a final way to concat strings with C++.

Using the strcat() function

This C-style method takes a destination string and appends a source string to it. This might sound just like the append() method, but there are a few key differences. First, the destination string must point to a character array already containing a C++ string. Second, that destination array must have enough space to contain the resulting concatenated string.

Let’s look at an example to understand how this method works:

#include <stdio.h>
#include <string.h>
 
int main ()
{
  char str[40];
  strcpy(str, "Professor ");
  strcat(str, "Jane Doe ");
  strcat(str, "teaches ");
  strcat(str, "stuff.");
 
  puts(str); // substitute for cout
  return 0;
}

Unlike the other methods, the strcat() function comes from the  string.h library, so we include that instead of iostream and the std namespace. For the sake of simplicity, we also include white spaces at the end of each string. You might notice that before we start concatenating, we use strcpy() to copy the first source string (“Professor”) into the destination array str since it’s initially empty:

If your destination array is too small — for example, if we’d defined str as char str[5] — you’ll get an error that says exited, segmentation fault. If you don’t know how long your output will be, you can initialize the string right away so the compiler can calculate the length of the array for you:

char init[] = "This is the init string";
char add[] = " that I am adding to now.";
strcat(init, add);
puts(init); // writes "This is the init string that I am adding to now."

There are, however, potential performance issues with strcat() that have to do with time complexity and how many times a program runs the function. That’s beyond the scope of this article, but we encourage you to check out Joel Spolsky’s blog post on the topic.

Now that we know several methods for concatenating C++ strings, let’s move on to use cases for concatenation.

Why Should We Concatenate?

Use cases for concatenation abound, but let’s take a look at three of the most common scenarios in which you will want to concat C++ strings. 

First, when we need to add a prefix to each of many words, we’ll want to use a C++ for loop to iterate over the words and concatenate the prefix to each string.

Above we saw a few examples of words being concatenated together to form a string. In real-world scenarios, we’ll often want to create a contiguous text out of three sentences, where each sentence is a string. To achieve this, we’ll simply need to use concatenation.

And third, you might come across a situation where you want to concatenate user input onto a prompt. Say you have a situation where a user needs to enter the birthdays of each of her family members. At the end of the program, we’d want to print the prompt for each individual along with the day entered, so we don’t get the birthdays mixed up. Here’s how that would work for one birthday: 

#include <iostream>
using namespace std;
int main()
{ 
    string s1, s2, result;
    s1 = "My dog's birthday is: ";

    cout << s1;
    getline (cin, s2);    // user inputs July 12, which is saved to s2

    result = s1 + s2;     // concat output and input
    cout << result;      // "My dog's birthday is: July 12"
    return 0;
}

We’ll now remember that the dog’s (and not the brother’s) birthday is July 12.

Now that we know how the concatenation of C++ strings can be useful, let’s touch on how to reverse C++ concatenation.

How to Reverse Concatenation

Let’s say we already have a concatenated string, and we actually want to split it up. How can we reverse concat strings? There are a few possible ways, with perhaps the most straightforward one involving strtok(), which lets you split up a string using a delimiter, or token. 

Another approach is with the std library’s  istringstream, which also lets you use supplied tokens to break a string into parts. Check out this Stack Overflow post to learn how to implement this method.

Become a C++ Developer

As a C++ developer you’ll often find yourself working with strings. While we only covered the basics of C++ string concatenation in this article, you can continue your learning journey by enrolling in our expert-taught C++ Nanodegree program. 

Start Learning