Question

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 to moving data
  • Destructor
  • Array index overload (e.g., str[2]): should be able to read or write the character in this position. Don't test for out-of-bounds indices.
  • Concatenation (+) operator: returns the concatenation of this string with the other. Does not modify either object.
  • Print function that works with cout

#ifndef __MYSTRING_H

#define __MYSTRING_H

#include <iostream>

using namespace std;

class MyString

{

friend ostream& operator<<(ostream&, const MyString&);

private:

char* str;

int len;

public:

MyString();

MyString(const char*);

MyString(const MyString&);

MyString(MyString&&);

const MyString& operator=(const MyString&);

const MyString& operator=(MyString&&);

~MyString();

int size() const { return len; }

char& operator[](int);

MyString operator+(const MyString&) const;

};

ostream& operator<<(ostream&, const MyString&);

#endif

ZOOM

#include <iostream>

#include <vector>

using namespace std;

#include "mystring.h"

int main()

{

//Test basic constructors and printing

MyString test1, test2("The quick brown fox jumps over the lazy dog ");

cout << "String 1: \"" << test1 << '"' << endl;

cout << "String 2: \"" << test2 << '"' << endl;

//Test [] operator

cout << "Char #41: " << test2[40] << endl;

test2[40] = 'h';

cout << "Changing char #41 to 'h': " << test2 << endl;

//Test copy constructor and assignment

MyString test3 = test2;

test2[40] = 'd';

cout << "Copy: " << test3 << endl;

test1 = test3 = test2;

cout << "Changing char #41 back: " << test3 << endl;

//Test + and move assignment

vector<MyString> vec;

vec.reserve(10);

vec.push_back(test1); //Calls copy constructor

for (int i = 1; i < test1.size(); i++)

if (test1[i - 1] == ' ')

vec.emplace_back(&test1[i]);

MyString test5;

cout << "Calling move assignment * " << vec.size() << ':' << endl;

for (int i = 0; i < vec.size(); i++)

test5 = test5 + vec[i];

cout << test5 << endl;

return 0;

}

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

#######################################
        MyString.cpp
#######################################
#include "MyString.h"

MyString::MyString(const char *charArr) {
        len = strlen(charArr);
        str = new char[len + 1];
        for (int i = 0; i < len; i++) {
                str[i] = charArr[i];
        }
        str[len] = '\0';
}

MyString::MyString() {
        len = 0;
        str = new char[len + 1];
        str[len] = '\0';
}


MyString::~MyString() {
        delete[] str;
}

int MyString::size() const {
        return len;
}
 
void MyString::set(const char *s) {
        delete[] str;
        len = strlen(s);
        str = new char[len + 1];
        for (int i = 0; i < len; i++) {
                str[i] = s[i];
        }
        str[len] = '\0';
}

char& MyString::operator[](int idx) {       
        return str[idx];
}

char& MyString::at(int i) {
        if(i < 0 || i >= len)
                throw std::invalid_argument( "OUT OF BOUNDS!" );
        return str[i];
}

MyString MyString::operator + (MyString const &other) {

        MyString res; 
        res.len = len + other.len;
        res.str = new char[res.len + 1];
        for (int i = 0; i < len; i++) {
                res.str[i] = str[i];
        }

        for (int i = len; i < res.len; i++) {
                res.str[i] = other.str[i];
        }
        res.str[len] = '\0';

        return res; 
} 
ostream & operator << (ostream &out, const MyString &s) {
        for (int i = 0; i < s.len; i++) {
                cout << s.str[i];
        }
        return out;
}



#######################################
          MyString.h
#######################################
#ifndef MYSTRING_H
#define MYSTRING_H

#include <iostream>
#include <cstring>
#include <cassert>
using namespace std;

class MyString
{
    public:
        MyString();
        MyString(const char *s);
        ~MyString();
        int size() const;
        void set(const char *s);
        char& at(int i);

        char& operator[](int idx);
        MyString operator + (MyString const &other);
        friend ostream & operator << (ostream &out, const MyString &s); 

    private:
        char *str;
        int len;
    };

#endif



#######################################
            main.cpp
#######################################
#include <iostream>
#include "MyString.h"

using namespace std;
#include <iostream>

#include <vector>

using namespace std;

int main()

{

//Test basic constructors and printing

MyString test1, test2("The quick brown fox jumps over the lazy dog ");

cout << "String 1: \"" << test1 << '"' << endl;

cout << "String 2: \"" << test2 << '"' << endl;

//Test [] operator

cout << "Char #41: " << test2[40] << endl;

test2[40] = 'h';

cout << "Changing char #41 to 'h': " << test2 << endl;

//Test copy constructor and assignment

MyString test3 = test2;

test2[40] = 'd';

cout << "Copy: " << test3 << endl;

test1 = test3 = test2;

cout << "Changing char #41 back: " << test3 << endl;

//Test + and move assignment

vector<MyString> vec;

vec.reserve(10);

vec.push_back(test1); //Calls copy constructor

for (int i = 1; i < test1.size(); i++)

if (test1[i - 1] == ' ')

vec.emplace_back(&test1[i]);

MyString test5;

cout << "Calling move assignment * " << vec.size() << ':' << endl;

for (int i = 0; i < vec.size(); i++)

test5 = test5 + vec[i];

cout << test5 << endl;

return 0;

}



Please upvote, as i have given the exact answer as asked in question. Still in case of any issues in code, let me know in comments. Thanks!

Add a comment
Know the answer?
Add Answer to:
Write a MyString class that stores a (null-terminated) char* and a length and implements all of...
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
  • 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:...

  • 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&...

  • 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...

  • 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...

  • 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...

  • 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...

  • In this lab, you will need to implement the following functions in Text ADT with C++...

    In this lab, you will need to implement the following functions in Text ADT with C++ language(Not C#, Not Java please!): PS: The program I'm using is Visual Studio just to be aware of the format. And I have provided all informations already! Please finish step 1, 2, 3, 4. Code is the correct format of C++ code. a. Constructors and operator = b. Destructor c. Text operations (length, subscript, clear) 1. Implement the aforementioned operations in the Text ADT...

  • In C++, develop a class that supports array rotation. Rotating an array is an operation where...

    In C++, develop a class that supports array rotation. Rotating an array is an operation where you shift all elements of the array some number of positions left or right, and elements that are shifted off of the left or right end of the array "wrap around" to the right or left end, respectively. For example, if we rotate the array [1, 2, 3, 4, 5] to the right by 1, we get the array [5, 1, 2, 3, 4]....

  • C++ When running my tests for my char constructor the assertion is coming back false and...

    C++ When running my tests for my char constructor the assertion is coming back false and when printing the string garbage is printing that is different everytime but i dont know where it is wrong Requirements: You CANNOT use the C++ standard string or any other libraries for this assignment, except where specified. You must use your ADT string for the later parts of the assignment. using namespace std; is stricly forbiden. As are any global using statements. Name the...

  • (C++) You are tasked with implementing a recursive function void distanceFrom(int key) on the IntList class...

    (C++) You are tasked with implementing a recursive function void distanceFrom(int key) on the IntList class (provided). The function will first search through the list for the provided key, and then, recursively, change all previous values in the list to instead be their distance from the node containing the key value. Do not update the node containing the key value or any nodes after it. If the key does not exist in the list, each node should contain its distance...

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