-3

I am working upon this problem.

Write a String class and overload the + operator to mix two strings such that a new string is created with one character from each string pieced together until all the characters are mixed. For example • "1234567890" + "QWERTYUIOP" = "1Q2W3E4R5T6Y7U8I9O0P"

Can you help me out in concatenating the characters of two strings?

This is the code I have written :

#include "stdafx.h"
#include<iostream>
#include<conio.h>
#include<string>
using namespace std;
class MY_String : public string
{
  public:
    char *rep;
    MY_String(){}
    MY_String(char *tem)
    {
      rep = new char[strlen(tem)+1] ;
      strcpy(rep,tem); 
    }
    MY_String operator + (const MY_String &rhs)
    {
      char *temp;MY_String obj11("1234567890");
      temp= new char[strlen(rep) + strlen(rhs.rep)+1];//cout<<"TEMP::"<<rhs.rep<<endl;
      temp = strcat(rep,rhs.rep);
      return MY_String(temp);
    }
};
int main()
{
    MY_String obj1("1234567890");
    MY_String obj2("QWERTYUIOP");
    MY_String obj3;

    obj3 = obj1+obj2;
    cout<<obj3.rep;
    return 0;

}

1 Answer 1

0

Assuming you know how to overload the operator+, the algorithm could be very simple.

 string A, B, Result;
 int As = A.size(), Bs = B.size();
 int MixingLenght = min(As,Bs);
 for (int index = 0; index < MixingLength; ++index)
 {
     Result += A[index];
     Result += B[index];
 }

Then you would have to decide what to do with the remaining part (if the strings are different in size). You could either ignore it, or append to the end of the Result.

10
  • Actually i have overloaded the '+' operator and you have used '+=' operator over here.So is it like one and the same thing?
    – Ankur
    Aug 28, 2012 at 11:37
  • No, these are two different things. Also, I am appending char in my solution (using +=). You could use std::string::append instead. Aug 28, 2012 at 11:39
  • Oh, you could use recurrence of +, of course, but seems like an overkill to me. I am not going to write your homework for you. Aug 28, 2012 at 11:43
  • Hey listen I am not asking you to complete my homework and neither i am a school kid.
    – Ankur
    Aug 28, 2012 at 11:46
  • I have written the code.The only problem i am facing is as to how to overload the '+' operator.
    – Ankur
    Aug 28, 2012 at 11:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.