Thursday, May 2, 2013

Operator overloading – String Concatenation C++




In ‘C’ or ‘C++’ the string concatenation not possible by adding two string like Java but often questions are given to do so using Operator Overloading + operator. Here is an example to solve this problem.



Example :
 #include<iostream.h>

  class String
      {
           private:
              char *s;
              int size;
           public:
               void getData()
                   {
                        cout<<"\n\tEnter Size : ";
                        cin>>size;
                        cin.ignore();
                        s = new char [size];
                        cout <<"\n\tEnter String:";
                        cin.getline(s, size);
                   }
               void display()
                   {
                        cout<<s;
                   }
               String operator +(String s2)         // ‘+’ operator overloaded
                   {
                        String ts;
                        ts.s = new char [size+s2.size];
                        for(int i = 0; s[i]!='\0';i++)
                            {
                                ts.s[i] = s[i];
                            }
                        for(int j = 0; s2.s[j]!='\0'; i++, j++)
                            {
                                ts.s[i] = s2.s[j];
                            }
                        ts.s[i] = '\0';
                        return ts;
                   }
      };

  int main()
      {
           String s1, s2, s3;
           s1.getData();
           s2.getData();
           cout<<"\n\tFirst String : ";
           s1.display();
           cout<<"\n\tSecond String : ";
           s2.display();

           s3 = s1 + s2; //overloading ++’ operator
           cout<<"\n\tAfter Concatenation : ";

           s3.display();
           return 0;
      }

No comments: