OneBite.Dev - Coding blog in a bite size

Concatenate A String In C++

Code snippet for how to Concatenate A String In C++ with sample and detail explanation

String concatenation is a very simple and frequently used operation in all programming languages, and C++ is no exception. This article will help you understand how to perform string concatenation in C++ using a working code example, and will explain each step in detail.

Code snippet for String Concatenation 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;
}

Code Explanation for String Concatenation in C++

Here we will break down how the code works step by step:

  1. At the beginning, the iostream and string libraries are included in the code. iostream is used for basic output and input operations, and string is used to use string data type in C++.
#include <iostream>
#include <string>
  1. Then, the main function is declared, wherein our operations will be performed.
int main(){
  1. The initial strings are declared as str1 and str2.
    std::string str1 = "Hello,";
    std::string str2 = "World!";
  1. Given that the two desired strings are now declared, we can concatenate them into a new string, str3. We simply add, or concatenate, them together and include a space for formatting.
    std::string str3 = str1 + " " + str2;
  1. To make sure that our operation was carried out correctly, the cout function is used. This function is used for output in C++. In this case, it will print the concatenated string and a new line after.
    std::cout << str3 << std::endl;
  1. Lastly, return 0; signifies the end of the main function.
    return 0;
}

After running the provided C++ string concatenation code, you will get “Hello, World!” as the output. The + operator in C++ allows us to concatenate strings exponentially, providing a level of power and utility that is crucial in many programming tasks.

c-plus-plus