Question

In: Computer Science

Using either your own C-string functions of Lab 7.1 or the ones from the standrd C++...

Using either your own C-string functions of Lab 7.1 or the ones from the standrd C++ cstring library, create a String class, which — while having minimal functionality — illustrates the use of and need for the canonical form.

Overview

Here is the .h file for the class (note the class name — String with a capital S; trying to force the use of the classname string was to much of an issue:

class String {
        friend std::ostream &operator <<(std::ostream &os, const String &s);
        
        friend String operator +(const String &s1, const String &s2);
public:
        String(const char *cs="");
        String(const String &s);
        ~String();
        String &operator =(const String &rhs);
        char &operator [](int index);
        String &operator +=(const String &s);
        
        int length() const;
        
private:
        char *cs;
};

I've also supplied a String_Exception class and an app for testing your class (it will be the test driver once I get it all into Codelab).

Implementation Notes

  • This exercise has potential name clashes with the standard C C-string library, named cstring, but originally named string.h — recall the naing conventions for the C++ wrapper libraries of standard C libraries. To avoid this, the files have been name mystring, e.g. mystring_app.cpp, mystring.h, etc. The only one that really affects you is the latter since you must #include it in your implementation file (mystring.cpp).
  • The String)const char *cs="") constructor allows one to create a String from C-string (and "..." literals, which are of type const char * – i.e., C-strings).
  • Operations on the cs buffer are performed using the C-string functions you wrote in lab 4.2.
    • Memory allocation involves making sure the cs data member (i.e., the pointer to the C-string buffer) is pointing to a sufficiently sized buffer.
      • For this implementation, we will use exact-sized buffer; i.e., enough elements in the char array to hold the characters of the C-string + the null terminator
      • This is relevant for the two constructors, the assignment operator and the += and + operators.
        • Using the String(const char *) constructor as an example:
          • when this constructor is called, the length of the argument is obtained using strlen and a buffer of the corresponding size is allocated (this can be done within the member initialization list)
          • the contents of the argument C-string is then copied to this new buffer using strcpy (this needs to be done in the body of the constructor; there is no way to work it into the member intialization list)
            String::String(const char *cs) : cs(new char[strlen(cs)+1) {    // the +1 is for the null terminator
                                                                            
        • Similar logic applies to the copy constructor, the assignment operator, and the += operator (you should be coding the + operator using the += operator as shown in class): in those three cases the source buffer (i.e., the C-string to be copied, assigned, or concatenated) will be the cs data member of another String object




          mystring.h
          #ifndef MYSTRING_H
          #define MYSTRING_H
          
          #include <iostream>
          
          
          class String {
                  friend std::ostream &operator <<(std::ostream &os, const String &s);
          //      friend bool operator ==(const String &s1, const String &s2);
                  friend String operator +(const String &s1, const String &s2);
          public:
                  String(const char *cs="");
                  String(const String &s);
                  ~String();
                  String &operator =(const String &rhs);
                  char &operator [](int index);
                  String &operator +=(const String &s);
          //      int find(char c) const;
                  int length() const;
          //      void clear();
          private:
                  char *cs;
          };
          
          #endif

mystring_app.cpp

#include <iostream>
#include <sys/sysinfo.h>
#include <cstdlib>

#include "mystring.h"

using namespace std;

int main() {
        String s = "Hello";

        cout << "s: " << s << " (" << s.length() << ")" << endl;

        cout << "s + \" world\": " << s + " world" << endl;

        cout << "s[1]: " << s[1] << endl;

        String s1 = s;          // making sure copy constructor makes deep copy
        String s2;
        s2 = s;                 // making sure assignment operator makes deep copy
        s[0] = 'j';
        cout << endl;
        cout << "s: " << s << " (" << s.length() << ")" << endl;
        cout << "s1: " << s1 << " (" << s1.length() << ")" << endl;
        cout << "s2: " << s2 << " (" << s2.length() << ")" << endl;
        cout << endl;

        for (int i = 0; i < 5; i++) {
                s += s;
                cout << "s: " << s << " (" << s.length() << ")" << endl;
        }
        cout << endl;

        for (int i = 0; i < 5; i++) 
                s += s;
        cout << "s: " << s << " (" << s.length() << ")" << endl;

        return 0;
}



mystring_exception.cpp
#ifndef MYSTRING_EXCEPTION
#define MYSTRING_EXCEPTION

#include <string>         // Note this is the C++ string class!

class String_Exception {
public:
    String_Exception(std::string what) : what(what) {}
        std::string getWhat() {return what;}
private:
    std::string what;
};

#endif

Solutions

Expert Solution

// mystring_exception.cpp

#ifndef MYSTRING_EXCEPTION
#define MYSTRING_EXCEPTION

#include <string> // Note this is the C++ string class!

class String_Exception {
public:
String_Exception(std::string what) : what(what) {}
std::string getWhat() {return what;}
private:
std::string what;
};

#endif


//end of mystring_exception.cpp

// mystring.h

#ifndef MYSTRING_H
#define MYSTRING_H

#include <iostream>


class String {
friend std::ostream &operator <<(std::ostream &os, const String &s);
// friend bool operator ==(const String &s1, const String &s2);
friend String operator +(const String &s1, const String &s2);
public:
String(const char *cs="");
String(const String &s);
~String();
String &operator =(const String &rhs);
char &operator [](int index);
String &operator +=(const String &s);
// int find(char c) const;
int length() const;
// void clear();
private:
char *cs;
};

#endif
//end of mystring.h

// mystring.cpp

#include "mystring.h"
#include "mystring_exception.cpp"
#include <cstring>
using namespace std;

String::String(const char *cs)
{
   this->cs = new char[strlen(cs)+1];
   strcpy(this->cs,cs);
}

String::String(const String &s)
{
   cs = new char[length()+1];
   strcpy(cs,s.cs);
}

String::~String()
{
   delete cs;
}

String& String::operator =(const String &rhs)
{
   if(this != &rhs)
   {
       delete cs;
       cs = new char[rhs.length()];
       strcpy(cs,rhs.cs);
   }

   return *this;
}

char & String::operator [](int index)
{
   try{
       if(index >=0 && index < length())
       {
           return cs[index];
       }else
           throw String_Exception("Index out of bounds");
   }catch(String_Exception &e)
   {
       cout<<e.getWhat();
   }
}

String & String::operator +=(const String &s)
{
   char *temp = new char[length()+s.length()+1];
   strcpy(temp,cs);
   strcat(temp,s.cs);

   delete cs;
   this->cs = temp;
   return *this;
}

int String::length() const
{
   return strlen(cs);
}

std::ostream &operator <<(std::ostream &os, const String &s)
{
   os<<s.cs;
   return os;
}

String operator +(const String &s1, const String &s2)
{
   char *temp = new char[s1.length()+s2.length()+1];

   strcpy(temp,s1.cs);
   strcat(temp,s2.cs);
   return String(temp);
}

//end of mystring.cpp

// mystring_app.cpp

#include "mystring.h"
#include <sys/sysinfo.h>
#include <cstdlib>

#include "mystring.h"

using namespace std;

int main() {
String s = "Hello";

cout << "s: " << s << " (" << s.length() << ")" << endl;

cout << "s + \" world\": " << s + " world" << endl;

cout << "s[1]: " << s[1] << endl;

String s1 = s; // making sure copy constructor makes deep copy
String s2;
s2 = s; // making sure assignment operator makes deep copy
s[0] = 'j';
cout << endl;
cout << "s: " << s << " (" << s.length() << ")" << endl;
cout << "s1: " << s1 << " (" << s1.length() << ")" << endl;
cout << "s2: " << s2 << " (" << s2.length() << ")" << endl;
cout << endl;

for (int i = 0; i < 5; i++) {
s += s;
cout << "s: " << s << " (" << s.length() << ")" << endl;
}
cout << endl;

for (int i = 0; i < 5; i++)
s += s;
cout << "s: " << s << " (" << s.length() << ")" << endl;

return 0;
}


//end of mystring_app.cpp

Output:


Related Solutions

For these of string functions, write the code for it in C++ or Python (without using...
For these of string functions, write the code for it in C++ or Python (without using any of thatlanguage's built-in functions) You may assume there is a function to convert Small string into the language string type and a function to convert your language's string type back to Small string type. 1. int [] searchA,ll(string in...str, string sub): returns an array of positions of sub in in...str or an one element array with -1 if sub doesn't exist in in...str
Look up the man pages for the following string functions from the C standard library, and...
Look up the man pages for the following string functions from the C standard library, and write implementations of each: strstr() Please explain the work please, thank you
Reflect on a strategy that was poorly executed either from your own organization or from a...
Reflect on a strategy that was poorly executed either from your own organization or from a researched example. Why did the implementation of strategy fail? What could have been done differently to produce more successful execution? Using this same organization, discuss the best method for entering a foreign market and explain your reasoning. If your company is already operating internationally, discuss its global strategy and how they successfully expanded. Also consider, if there are additional markets they should expand into...
Java - In this lab, you will be writing your own method using the brute force...
Java - In this lab, you will be writing your own method using the brute force algorithm, to solve a second degree polynomial. This method will take in four parameters, three coefficients, and one constant, and it will have the following signature: public static String bruteForceEquationSolver(int one, int two, int three, int constant){} The equation you are trying to solve is of the following format, given the parameters stated above: (constant) = (one) * x + (two) * y +...
how to accept string from shared memory using c language ?
how to accept string from shared memory using c language ?
This assignment is to give you practice using enums, string variables, and string functions. In order...
This assignment is to give you practice using enums, string variables, and string functions. In order to get full credit for the program you must use these three topics. You are to write a program that will read a series of names of people from a data file that has been created with extra blank spaces and reformat the names into a standardized format. The datafile is mp6names.txt. It is arranged with the information for one person on each line....
Using the string functions below, write new functions to do the following, and test them in...
Using the string functions below, write new functions to do the following, and test them in your main() function: Determine whether the first or last characters in the string are any of the characters a, b, c, d, or e. Reverse a string Determine whether a string is a palindrome (spelled the same way forward or backward FUNCTIONS REFERENCE: string myString = "hello"; // say we have a string… // … we can call any of the following // string...
Using the Iris dataset in R; PLEASE CREATE YOUR OWN FUNCTION USING FORMULAS INTEAD OF FUNCTIONS...
Using the Iris dataset in R; PLEASE CREATE YOUR OWN FUNCTION USING FORMULAS INTEAD OF FUNCTIONS THAT ARE BUILT IN R ,,,,,PLEASE TRY PLEASE a Carry out a hypothesis to test if the population sepal length mean is 6.2 at α = 0.05. Interpret your results. b Carry out a hypothesis to test if the population sepal width mean is 4 at α = 0.05. Interpret your results. c Carry out a hypothesis to test if the population sepal width...
What lab tests can Vitamin C interact with? LIST FIVE TESTS and EXPLAIN what these lab tests are- and THEIR INTERACTION with Vitamin C in your own words.
 What lab tests can Vitamin C interact with? LIST FIVE TESTS and EXPLAIN what these lab tests are- and THEIR INTERACTION with Vitamin C in your own words.
Implement two functions in C language: stringLength() - Takes a pointer to a string, and a...
Implement two functions in C language: stringLength() - Takes a pointer to a string, and a pointer to an int variable. It computes the length of the string and updates the int variable with the length. stringCopy() - Copies one string onto another using pointers #include<stdio.h> #define MAX_STR_LEN 2048 void stringLength(char *str, int *len) { // This function computes the length of the string // at the address in the pointer *str. Once the length // has been determined, it...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT