Fourteen98

String class to prissy

Sep 28th, 2021
973
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2.  
  3. class MyString {
  4.   public:
  5.     char *string;
  6.     int length;
  7.     MyString();
  8.     MyString(const char *str);
  9.     ~MyString();
  10.     void append(MyString obj);
  11.     int  len();
  12.     void prepend(MyString obj);
  13. }; // MyString
  14.  
  15. MyString::MyString() {
  16.   length = 1;
  17.   string = new char[length];
  18.   string[0] = '\0';
  19. } // MyString
  20.  
  21. MyString::MyString(const char *str) {
  22.   for (length = 0; str[length] != '\0';
  23.       length++);
  24.   length++;
  25.   string = new char[length];
  26.   for(int i = 0; i < length; i++)
  27.     string[i] = str[i];
  28. } // MyString
  29.  
  30. MyString::~MyString() {
  31.   if (string != NULL)
  32.     delete [] string;
  33.   string = NULL;
  34. } // ~MyString
  35.  
  36. void MyString::append(MyString obj) {
  37.   int size = length+obj.length-1;
  38.   char *temp = new char[size];
  39.   for (int i = 0; i < length; i++)
  40.     temp[i] = string[i];
  41.   for (int i = 0; i < obj.length; i++)
  42.     temp[i+length-1] = obj.string[i];
  43.   delete [] string;
  44.   length = size;
  45.   string = temp;
  46. } // append
  47. int MyString::len(){
  48.     return length - 1;
  49. }
  50.  
  51.  
  52. int main() {
  53.   MyString first = MyString("hello");
  54.  
  55.   std::cout << first.string <<" length is: " << first.len()<< std::endl;
  56.   MyString second = MyString("World");
  57.   std::cout << second.string << " length is: "  << second.len() << std::endl;
  58.   first.append(second);
  59.   std::cout << "After the append function" << std:: endl;
  60.   std::cout << first.string << " length is: " << first.len() << std::endl;
  61.  
  62.   return 0;
  63.  } // main
  64.  
RAW Paste Data