C++ String Concatenation - string data type

Hey! Good day, Now we are learning C++ String Concatenation. In the first, we learn C++ string then will learn string concatenation and its another data type of C++.

String is a Data type for storing a plain text.

A string variable contains a set of/ collection of characters surrounded with double-quotes.

So, Now here i am explaining a Example:

Create a variable of data type string and assign it a value.

#include <iostream>
using namespace std;

int main() {
  string greet = "Hello! Dear";
  cout << greet;
  return 0;
}

To use strings, you much include the additional header file, C++ has own extra string library, named <string.h>, so, example below.

#include <iostream>
#include <string.h>
using namespace std;

int main() {
  string greet = "Hello! Dear";
  cout << greet;
  return 0;
}

So, see output:

Hello! Dear

I hope you understand! The data type string, Now I am talking about string Concatenation. How to c++ string concat?

So, Follow the page will upload updates on FB Page.

C++ String Concat

The + operator is using string variables to make concatenation. the example below and both the methods are valid. method 1:

So, Example:

#include <iostream>
#include <string.h>
using namespace std;
 
int main () {
  string firstNam = "John ";
  string lastNam = "Hebrew";
  string fullNam = firstNam + lastNam;
  cout << fullName;
  return 0;
}

So, the method 2 is:

#include <iostream>
#include <string.h>
using namespace std;
 
int main () {
  string firstNam = "John";
  string lastNam = "Hebrew";
  string fullNam = firstNam + " " + lastNam;
  cout << fullName;
  return 0;
}

Then, Both of the output is same:

John Hebrew

But the third method is different from other both. method 1 and method 2. In the third method, we will use a built function. named Append.

Append

In C++, String is actually an object, which contain functionality that can perform certain operations on string variables. For example,, you can also concatenate text / string with the append() function example below:

So, See an Example:

#include <iostream>
#include <string.h>
using namespace std;
 
int main () {
  string firstNam = "John ";
  string lastNam = "Hebrew";
  string fullNam = firstNam.append(lastNam);
  cout << fullNam;
  return 0;
}

It depends on you, you like this method with append() function or you like the method of the first two examples. I suggest that this method append() function because this method is much faster. However, for testing and such as. it might be an easier way to just use +.

So, I want to tell you that, theCodeMaster has uploaded Complete C++ Course on this Website, Just like C++ Intro, Syntax, output, input, comments, data types, variables, and many more… Don’t forget to give feedback in the below section Comment…

By Usama Arshad

It's me Usama Arshad working as a Lecturer C++. I am a student of BSIT.

Leave a Reply

Your email address will not be published. Required fields are marked *