OneBite.Dev - Coding blog in a bite size

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:

  1. 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.

  2. The int main() is the main function where the program execution begins.

  3. Within the main function, we declare three strings str1, str2, and str3. str1 is initialized with the value "Hello ", and str2 is initialized with the value "World".

  4. The fourth line of the main function combines str1 and str2 using the ’+’ operator and assigns the result to str3.

  5. After that, str3 is printed to the console using std::cout << str3 << std::endl;. This line outputs the value of str3 followed by a new line.

  6. 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!

c-plus-plus