Combine Two Strings In C++
Code snippet for how to Combine Two Strings In C++ with sample and detail explanation
In this article, we are going to learn how to combine two strings in C++. The process is quite easy and straightforward, especially if you are familiar with basic C++ programming.
Code snippet to Combine Two Strings
Here is a simple code snippet that demonstrates how to concatenate two strings in C++:
#include<iostream>
#include<string>
int main() {
std::string str1 = "Hello ";
std::string str2 = "World";
std::string str3 = str1 + str2;
std::cout << str3 << std::endl;
return 0;
}
When you run this program, it will output: Hello World
.
Code Explanation to Combine Two Strings
Now let’s break down this code step by step:
-
The program begins with
#include<iostream>
and#include<string>
. The first line is a preprocessor command, which tells a C++ compiler to include iostream file before going to the actual compilation. The second line tells the compiler to include the string file. -
The
int main()
is the main function where the program execution begins. -
Within the main function, we declare three strings
str1
,str2
, andstr3
.str1
is initialized with the value"Hello "
, andstr2
is initialized with the value"World"
. -
The fourth line of the
main
function combinesstr1
andstr2
using the ’+’ operator and assigns the result tostr3
. -
After that,
str3
is printed to the console usingstd::cout << str3 << std::endl;
. This line outputs the value ofstr3
followed by a new line. -
Finally, the
return 0;
statement is the “exit status” of the program. In C++, returning zero indicates that the program has executed successfully.
And that’s it! As you can see, combining strings in C++ is very intuitive and simple. Just remember to include the string
library and use the ’+’ operator. Happy coding!