All About C++

Get Pure Concepts of C++

Sunday, 5 June 2016

How to concatenate two or more strings of different objects in C++ with example code

In concatenation, we concatenate two or more strings together. Concatenation syntax in C++ is:
strcat(str1,str2);
Here:
str1 and str2 are two strings which are concatenated and the result is stored in left side’s string which is in above case is str1,so here result will be stored in str1.
Example Code:
In this example code strings which belong to two different objects are concatenated.

#include<iostream>
using namespace std;
#include<string>
#include<stdlib.h>
class string
{ private:
enum {sz=80};
char str[sz];
public:
            string()
            { strcpy(str," ");}
            string(char s[])
            { strcpy(str,s);  }
            void display() const
            {cout<<str;}
string operator +(string ss)  const
{
            string temp;
            if(strlen(str) + strlen(ss.str)<sz)
            {
                        strcpy(temp.str,str);
                        strcat(temp.str,ss.str);
            }
            else
            {cout<<"string over fllow";
            exit(1); }
            return temp;
}
};
int main()
{ string s1 ="merry christmiss!";
string s2 ="happy new year!";
string s3;

s1.display();
s2.display();
s3.display();
s3=s1+s2;
s3.display();
cout<<endl;
return 0;
}


If you have any query you can comment or contact with us,Thanks

No comments:

Post a Comment