Extra 5% OFF Use Code: OL05
Free Shipping over ₹999

Concatenation string

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:

  • str1 is assigned the value "Ocean Labz ".
  • str2 is 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 of str2 to the end of str1.
  • After this operation, str1 becomes "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 string add by concatenating str1 and str2 using the + operator.
  • The combined string ("Ocean Labz space for innovation") is stored in add.
  • cout << add << endl; prints the concatenated string to the console.

    Leave a Reply

    Your email address will not be published.

    Need Help?