C++ String Concatenation Example
String Concatenation in C++
String concatenation is the process of combining two or more strings into a single string. In C++, there are multiple ways to concatenate strings. Let's look at an example of string concatenation in C++ and explain each step:
#include <iostream>
#include <string>
int main() {
std::string str1 = "Hello";
std::string str2 = "World";
std::string result = str1 + " " + str2;
std::cout << result << std::endl;
return 0;
}
Include necessary libraries: In the code example, we include the
<iostream>
and<string>
libraries. The<iostream>
library is needed for input/output operations, and the<string>
library is used for string manipulation.Declare string variables: We declare three string variables:
str1
,str2
, andresult
.str1
is initialized with the value "Hello",str2
is initialized with the value "World", andresult
is the variable that will hold the concatenated string.Concatenate the strings: The concatenation happens on the line
std::string result = str1 + " " + str2;
. The+
operator is used to concatenate the strings. In this example, we concatenatestr1
, a space (" "), andstr2
to form the string "Hello World". The result is stored in theresult
variable.Output the concatenated string: We output the concatenated string using
std::cout << result << std::endl;
. The<<
operator is used to send the value ofresult
to thestd::cout
object, which represents the standard output. Finally,std::endl
is used to insert a newline character.Return 0: The
return 0;
statement is used to indicate the successful execution of the program.
This is a basic example of string concatenation in C++. There are other ways to concatenate strings, such as using the append()
function or the +=
operator.