![]() |
VOOZH | about |
String concatenation refers to the process of combining two or more strings into a single string. Generally, one string is appended at the end of the other string.
The simplest method to concatenate two strings in C++ is by using + operator. Let's take a look at an example:
Hello World
In the above program, '+' operator combines two string objects and returns the resulting concatenated string. However, this method only works for C++ style strings (std::string) and is not applicable to C-style string (character array).
There are also many other different ways to concatenate two strings in C++:
The string append() function is a member of the string class that is used to concatenate two string objects in C++. It provides an efficient way to concatenate two strings. We use this method when we need efficiency or in-place concatenation of std::string objects. In-place concatenation refers to modifying an existing string by appending another string to it without creating a new string object.
Hello World
The strcat() function is a standard library function in C that is also available in C++. It is used to concatenate (append) one C-style string (character array) to another and adds a null terminator at the end. It is defined inside the <cstring> header file. This method is mostly used when we are working with C-style strings.
Hello World
In this method, characters from one string are appended manually one by one to another while iterating through both strings using loops. The final result is a concatenated string that combines both original string.
Use this method for manual control over concatenation, such as with custom string structures or some processing before concatenation. It is also suitable when direct library functions aren't available or for specific logic during concatenation.
Hello World