Mark As Completed Discussion

String Concatenation

In C++, you can concatenate strings using the + operator or the += operator.

Here's an example:

TEXT/X-C++SRC
1#include <iostream>
2#include <string>
3
4int main() {
5  std::string str1 = "Hello";
6  std::string str2 = "World!";
7
8  std::string result = str1 + str2;
9
10  std::cout << result << std::endl;
11
12  return 0;
13}

In this example, we have two strings str1 and str2. We use the + operator to concatenate them and store the result in the result variable. Finally, we print the concatenated string result.

String concatenation is useful when you want to combine multiple strings into a single string. It allows you to build more complex strings by joining smaller segments together.

Note that when concatenating strings, a new string is created to hold the combined value. The original strings str1 and str2 remain unchanged.

You can also use the += operator to concatenate a string with another string and assign the result back to the original string.

Try experimenting with different strings and see how string concatenation works in C++.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment