In this example , we will add two strings
#include <iostream>
using namespace std;
int main(){
string str1 = "Ocean Labz ";
string str2 = "space for innovation";
// concatenation string by append() method
// str1.append(str2);
// cout<<str1<<endl;
//concatenation string by '+' operator
cout<<"+ operator"<<endl;
string add = str1 + str2;
cout<<add<<endl;
}
Output:
+ operator
Ocean Labz space for innovation
Explanation:
Step1: String Declarations
string str1 = "Ocean Labz ";
string str2 = "space for innovation";
Here, two strings are declared and initialized:
str1is assigned the value"Ocean Labz ".str2is assigned the value"space for innovation".
Step2: Concatenation Using append() (Commented Out)
// concatenation string by append() method
// str1.append(str2);
// cout<<str1<<endl;
This section is commented out, but it shows how to use the append() method to concatenate str2 to str1. Here’s how it works:
str1.append(str2)appends the contents ofstr2to the end ofstr1.- After this operation,
str1becomes"Ocean Labz space for innovation". - The result would then be printed using
cout.
Uncommenting this part would concatenate the two strings in str1 using the append() method and output the combined string.
Step3: Concatenation Using the + Operator
cout << "+ operator" << endl;
string add = str1 + str2;
cout << add << endl;
This part shows concatenation using the + operator:
string add = str1 + str2;creates a new stringaddby concatenatingstr1andstr2using the+operator.- The combined string (
"Ocean Labz space for innovation") is stored inadd. cout << add << endl;prints the concatenated string to the console.
