C++ String Concatenation

In this section, we will learn about C ++ String Concatenation, what it does, how it works, and will also see its programs.

What is the String Concatenation?

The + operator can be used to form a new string between strings to link them together. That is known as concatenation.

There are different ways to perform concatenation of strings. We will be discussing each one of them.

Using strcat() function.

The strcat) (function is set to the header file of “string.h.”

Syntax:           

The string init and add should be of character array(char *). This function concatenates the added string to the init string end.

Example:

Output:

C++ String Concatenation

Using append() function.

A string in C++ is actually an object that contains functions to perform some string operations. For, e.g., you can also use the function append() to concatenate strings.

Syntax:-

Here str is the std::string class object, which is an instantiation of the basic string class template which uses char as a type of its character. At the end of the0 init string, the append function appends the add(variable) string.

In the above example, we added space on output after firstName to create a space between Mike and Johnson. You can, however, also add a space with quotes (“or”):

Output:

C++ String Concatenation

Whether you want to use + or append() is up to you. The key difference between the two is that the function append() is much quicker. Nonetheless, it may be better to only use + for checking and so on.

Using ‘+’ Operator

Syntax:

It is the simplest way to merge two strings. The + operator actually puts the two strings together and returns a concatenated string.

Example:

Output:

C++ String Concatenation

Example

Output:

C++ String Concatenation

Without using function

For this, we concatenate two separate strings without using strcat() as the concatenation function.

Example:

Output:

C++ String Concatenation

Pin It on Pinterest

Share This