Question

2. (50 marks) A string in C++ is simply an array of characters with the null...

2. (50 marks) A string in C++ is simply an array of characters with the null character(\0)

used to mark the end of the string. C++ provides a set of string handling function in

<string.h> as well as I/O functions in <iostream>. With the addition of the STL (Standard

Template Library), C++ now provides a string class.

But for this assignment, you are to develop your own string class. This will give you a

chance to develop and work with a C++ class, define constructors and destructors, define

member functions outside of the class body, develop a copy constructor and assignment

operator (and understand why!), work with C-Style strings and pointers, dynamically

allocate memory and free it when done.

Of course, you must also do suitable testing which implies writing a main function that

uses your new string class. Submit your assignment under URCourses.The following is the skeleton of the Mystring class declaration. Mystring.h file is

provided. You must produce the Mystring.cpp and main.cpp files.

class Mystring

{

private:

char *pData;

//pointer to simple C-style representation of the string

//(i.e., sequence of characters terminated by null)

//pData is only a pointer. You must allocate space for

//the actual character data

int length;

//length of the string

//…

//possibly other private data

public:

MyString();

//constructor --- create empty string

MyString(char *cString); //constructor --- create a string whose data is a copy of

//cString

~MyString();

//destructor -- don't forget to free space allocated by the constructor

//i.e., the space allocated for the character data

MyString(MyString const& s); //override the default copy constructor --- why?

//important -- think about it -- possible test question

MyString operator = (MyString const& s); //override default assignment operator

void Put();

//output string

void Reverse();

//reverse the string

MyString operator + (MyString const& s); //concatenation operator

// …

//other useful member functions

//as you wish

};

In addition, prepare a graphical explanation of each of your member functions. (Pseudo

code or flowchart or some diagram to show your design.)#ifndef MYSTRING_H

#define MYSTRING_H

class MyString

{

private:

char *pData;

//pointer to simple C-style representation of the string

//(i.e., sequence of characters terminated by null)

//pData is only a pointer. You must allocate space for

//the actual character data

int length;

//length of the string

// …

//possible other private data

public:

MyString();

//constructor --- create empty string

MyString(char *cString); //constructor --- create a string whose data is a copy of

//cString

~MyString();

//destructor -- don't forget to free space allocated by the constructor

//i.e., the space allocated for the character data

MyString(MyString const& s); //override the default copy constructor --- why?

//important -- think about it -- possible test question

MyString operator = (MyString const& s); //override default assignment operator

void Put();

//output string

void Reverse();

//reverse the string

MyString operator + (MyString const& s); //concatenation operator

// …

//other useful member functions

//as you wish

};

#endif // MYSTRING_H

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Pseudocode for the functions of MyString class:

MyString():
   pData -> NULL
   length -> 0

MyString(char* cString):
   len -> length(cString)
   Allocate memory to pData
   pData -> cString
   length -> len

MyString(MyString const& s):
   len -> s.length
   Allocate memory to pData
   pData -> s.pData
   length -> len

operator=(MyString const& s):
   Free previously allocated string memory
   len -> s.length
   Allocate memory to pData
   pData -> s.pData
   length -> len
   Return this pointer

operator+(MyString const& s):
   len -> length + s.length
   Reallocate memory to pData
   pData[this.length:] -> s.length
   length ->len
   Return this pointer

Put():
   Display pData to console

Reverse():
   low -> 0
   high -> length - 1
   while low < high:
       swap (pData[low], pData[high])
       low = low + 1
       high = high - 1

~MyString():
   Free memory allocated to pData

Declaration of MyString class (mystring.h):

#ifndef MYSTRING_H
#define MYSTRING_H

class MyString
{
private:
   char *pData;   //   Contains the string
   int length;       //   Length of the string
public:
   MyString();       //   Default constructor
   MyString(char *cString);       //   Parameterized constructor
   MyString(MyString const& s);   //   Copy constructor
  
   MyString operator=(MyString const& s);   //   Assginment operator
   MyString operator+(MyString const& s);   //   Concatenation operator
   void Put();       //   Display the string
   void Reverse();   //   Reverse the string
  
   ~MyString();   //   Destructor
};

#endif   //   MYSTRING_H

Definitions of member functions of MyString class (mystring.cpp):

#include <iostream>
#include <string.h>
#include "mystring.h"

MyString::MyString()
{
   this->pData = NULL;   //   Initializing pointer to NULL
   this->length = 0;   //   Current length of string is zero
}

MyString::MyString(char *cString)
{
   int len = strlen(cString);
   this->pData = (char*)malloc(sizeof(char) * len);   //   Allocate memory to string
   strcpy(this->pData, cString);   //   Copy cString to pData
   this->length = len;               //   Update length
}

MyString::MyString(MyString const& s)
{
   this->pData = (char*)malloc(sizeof(char) * s.length);   //   Allocate memory to string
   strcpy(this->pData, s.pData);   //   Copy string in s to pData
   this->length = s.length;       //   Update length
}

MyString MyString::operator=(MyString const& s)
{
   int len = s.length;               // Calculate length of new string
   this->pData = (char*)realloc(this->pData, sizeof(char) * len);   //   Reallocate memory for the new string
   strcpy(this->pData, s.pData);   //   Copy string in s to pData
   this->length = s.length;       //   Update length
   return *this;
}

MyString MyString::operator+(MyString const& s)
{
   int len = this->length + s.length;   //   Calculate length of new string
   this->pData = (char*)realloc(this->pData, sizeof(char) * len);   //   Reallocate memory to occupy the new string
   strcpy(this->pData + this->length, s.pData);   //   Append string in s behind the string already in pData
   this->length = len;                   //   Update length
   return *this;
}

void MyString::Put()
{
   std::cout << pData;
}

void MyString::Reverse()
{
   int low = 0, high = this->length-1;
   while(low < high)
   {
       //   Swap the two ends
       char temp = pData[low];
       pData[low] = pData[high];
       pData[high] = temp;
      
       //   Update the indexes
       ++low, --high;
   }
}

MyString::~MyString()
{
   free(this->pData);       //   Free memory allocateed to pData
}

Driver function (main.cpp):

#include <iostream>
#include "mystring.h"

using namespace std;

int main()
{
   MyString str = "Hello";
   MyString str1;   //   Default Constructor
   MyString str2("Hello");   //   Parameterized constructor
   MyString str3 = str;   //   Copy constructor
   str1 = str;

   str.Reverse();
   str.Put();
   cout << endl;
  
   str1.Put();
   cout << endl;

   str2 = str2 + str;
   str2.Put();
   cout << endl;

   str3.Put();
   cout << endl;
   return 0;
}

Add a comment
Know the answer?
Add Answer to:
2. (50 marks) A string in C++ is simply an array of characters with the null...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Write a MyString class that stores a (null-terminated) char* and a length and implements all of...

    Write a MyString class that stores a (null-terminated) char* and a length and implements all of the member functions below. Default constructor: empty string const char* constructor: initializes data members appropriately Copy constructor: prints "Copy constructor" and endl in addition to making a copy Move constructor: prints "Move constructor" and endl in addition to moving data Copy assignment operator: prints "Copy assignment" and endl in addition to making a copy Move assignment operator: prints "Move assignment" and endl in addition...

  • C++ Write a MyString class that stores a (null-terminated) char* and a length and implements all...

    C++ Write a MyString class that stores a (null-terminated) char* and a length and implements all of the member functions below. Submit your completed source (.cpp) file. Default constructor: empty string const char* constructor: initializes data members appropriately Copy constructor: prints "Copy constructor" and endl in addition to making a copy Move constructor: prints "Move constructor" and endl in addition to moving data Copy assignment operator: prints "Copy assignment" and endl in addition to making a copy Move assignment operator:...

  • Objectives You will implement and test a class called MyString. Each MyString object keeps track ...

    Objectives You will implement and test a class called MyString. Each MyString object keeps track of a sequence of characters, similar to the standard C++ string class but with fewer operations. The objectives of this programming assignment are as follows. Ensure that you can write a class that uses dynamic memory to store a sequence whose length is unspecified. (Keep in mind that if you were actually writing a program that needs a string, you would use the C++ standard...

  • C++ LinkedList I need the code for copy constructor and assignment operator #include <iostream> #include <string> using namespace std; typedef string ItemType; struct Node {    ItemType va...

    C++ LinkedList I need the code for copy constructor and assignment operator #include <iostream> #include <string> using namespace std; typedef string ItemType; struct Node {    ItemType value;    Node *next; }; class LinkedList { private:    Node *head;    // You may add whatever private data members or private member functions you want to this class.    void printReverseRecursiveHelper(Node *temp) const; public:    // default constructor    LinkedList() : head(nullptr) { }    // copy constructor    LinkedList(const LinkedList& rhs);    // Destroys all the dynamically allocated memory    //...

  • Help C++ Write a string class. To avoid conflicts with other similarly named classes, we will...

    Help C++ Write a string class. To avoid conflicts with other similarly named classes, we will call our version MyString. This object is designed to make working with sequences of characters a little more convenient and less error-prone than handling raw c-strings, (although it will be implemented as a c-string behind the scenes). The MyString class will handle constructing strings, reading/printing, and accessing characters. In addition, the MyString object will have the ability to make a full deep-copy of itself...

  • You are to implement a MyString class which is our own limited implementation of the std::string...

    You are to implement a MyString class which is our own limited implementation of the std::string Header file and test (main) file are given in below, code for mystring.cpp. Here is header file mystring.h /* MyString class */ #ifndef MyString_H #define MyString_H #include <iostream> using namespace std; class MyString { private:    char* str;    int len; public:    MyString();    MyString(const char* s);    MyString(MyString& s);    ~MyString();    friend ostream& operator <<(ostream& os, MyString& s); // Prints string    MyString& operator=(MyString& s); //Copy assignment    MyString& operator+(MyString&...

  • SCREENSHOTS ONLY PLEASE!!! DON'T POST ACTUAL CODE PLEASE LEAVE A SCREENSHOT ONLY! ACTUAL TEXT IS NOT NEEDED!!! myst...

    SCREENSHOTS ONLY PLEASE!!! DON'T POST ACTUAL CODE PLEASE LEAVE A SCREENSHOT ONLY! ACTUAL TEXT IS NOT NEEDED!!! mystring.h: //File: mystring1.h // ================ // Interface file for user-defined String class. #ifndef _MYSTRING_H #define _MYSTRING_H #include<iostream> #include <cstring> // for strlen(), etc. using namespace std; #define MAX_STR_LENGTH 200 class String { public: String(); String(const char s[]); // a conversion constructor void append(const String &str); // Relational operators bool operator ==(const String &str) const; bool operator !=(const String &str) const; bool operator >(const...

  • The function should have a class name CPizza that will have three constructors (default, type, and...

    The function should have a class name CPizza that will have three constructors (default, type, and copyl, public functions to use and implement are noted for you in the starter kit, and private member variables (all which are allocated dynamically). The private member variables include the three different sizes of pizza (Large, Medium, and Small), cost, a bool delivery, name, and delivery fee. The prices of the pizzas' are $20. $15, and $10 for large, medium, and small respectively. The...

  • please write the code in C++ 2 Base class File 3 Derived class PDF 3.1 Class...

    please write the code in C++ 2 Base class File 3 Derived class PDF 3.1 Class declaration • The class PDF inherits from File and is a non-abstract class 1. Hence objects of the class PDF can be instantiated. 2. To do so, we must override the pure virtual function clone) in the base class • The class declaration is given below. • The complete class declaration is given below, copy and paste it into your file. . It is...

  • A hard c++ problem ◎Write a c++ program”Student.h”include Private data member, string firstName; string lastName; double...

    A hard c++ problem ◎Write a c++ program”Student.h”include Private data member, string firstName; string lastName; double GPA(=(4.0*NumberOfAs+3.0*NumberOfBs+2.0*NumberOfCs+1.0*NumberOfDs)/( As+Bs+Cs+Ds+Fs)); Public data member, void setFirstName(string name); string getFirstName() const; void printFirstName() const; void getLastName(string name); string getLastName() const; void printLastName() const; void computeGPA(int NumberOfAs,int NumberOfBs,int NumberOfCs,int NumberOfDs,int NumberOfFs); double getGPA() const; double printGPA() const; A destructor and an explicit default constructor initializing GPA=0.0 and checking if GPA>=0.0 by try{}catch{}. Add member function, bool operator<(const Student); The comparison in this function based on...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT