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

  2. Declare string variables: We declare three string variables: str1, str2, and result. str1 is initialized with the value "Hello", str2 is initialized with the value "World", and result is the variable that will hold the concatenated string.

  3. 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 concatenate str1, a space (" "), and str2 to form the string "Hello World". The result is stored in the result variable.

  4. Output the concatenated string: We output the concatenated string using std::cout << result << std::endl;. The << operator is used to send the value of result to the std::cout object, which represents the standard output. Finally, std::endl is used to insert a newline character.

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