Rodex_

StringClass

Nov 3rd, 2018
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. // Exercise1.cpp : Diese Datei enthält die Funktion "main". Hier beginnt und endet die Ausführung des Programms.
  2. //
  3. #include <iostream>
  4.  
  5. class String
  6. {
  7. public:
  8.     String (const char * string)
  9.     {
  10.         m_length = strlen(string);
  11.         m_value = new char[m_length + 1];
  12.         memcpy(m_value, string, m_length + 1);
  13.     }
  14.  
  15.     ~String()
  16.     {
  17.         delete[] m_value;
  18.     }
  19.  
  20.     size_t GetLength() const
  21.     {
  22.         return m_length;
  23.     }
  24.  
  25.     const char* c_str() const
  26.     {
  27.         return m_value;
  28.     }
  29.  
  30.     void Concatenate(const String& str)
  31.     {
  32.         Concatenate(str.c_str());
  33.     }
  34.  
  35.     ///Used this solution: https://puu.sh/BVyEB/f697b8b781.png
  36.     void Concatenate(const char* str)
  37.     {
  38.         const auto n_length = strlen(str);
  39.         const auto n_string = new char[m_length + n_length + 1]; //Add the old length and the new length + 1 for \0
  40.         memcpy(n_string, m_value, m_length);
  41.         memcpy(n_string + m_length, str, n_length + 1);
  42.         delete[] m_value; //Delete the old HeapMem to save the new pointer in the next line
  43.         m_value = n_string;
  44.         m_length += n_length;
  45.     }
  46.  
  47.  
  48. private:
  49.     char* m_value;
  50.     size_t m_length;
  51. };
  52.  
  53. int main()
  54. {
  55.     const auto str = "MyVision";
  56.     const String yourString(str);
  57.  
  58.     String myString("Hello");
  59.     myString.Concatenate("World");
  60.  
  61.     const auto m_length = myString.GetLength();
  62.     const auto y_length = yourString.GetLength();
  63.     std::cout << m_length << std::endl;
  64.     std::cout << y_length << std::endl;
  65.    
  66.     myString.Concatenate(yourString);
  67.     const auto b_length = myString.GetLength();
  68.     std::cout << b_length << std::endl;
  69.  
  70.     const char* cStr = myString.c_str();
  71.     std::cout << cStr;
  72. }
Advertisement
Add Comment
Please, Sign In to add comment