Advertisement
35657

Untitled

May 21st, 2023
662
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.95 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2.  
  3. #include <iostream>
  4. #include <cstring>
  5.  
  6.  
  7. using namespace std;
  8.  
  9. class String {
  10.  
  11. public:
  12.  
  13.     String() : size(0), capacity(15), str(new char[15]) {}
  14.  
  15.     String(const int string_capacity) : size(0), capacity(string_capacity), str(new char[string_capacity]) {}
  16.  
  17.     String(const char new_str[]) {
  18.         capacity = strlen(new_str) + 1;
  19.         str = new char[capacity];
  20.         strcpy(str, new_str);
  21.         size = capacity - 1;
  22.     }
  23.  
  24.     void SetString(const char new_str[]) {
  25.         int new_space = strlen(new_str) + 1;
  26.         if (capacity < new_space) {
  27.             delete[] str;
  28.             capacity = new_space;
  29.             str = new char[capacity];
  30.         }
  31.         strcpy(str, new_str);
  32.         size = capacity - 1;
  33.     }
  34.  
  35.     const char* GetString() {
  36.         return str;
  37.     }
  38.  
  39.     void SetChar(const int index, const char ch) {
  40.         if (index < 0 || index >= size) {
  41.             cout << "Invalid index" << endl;
  42.             return;
  43.         }
  44.         str[index] = ch;
  45.     }
  46.  
  47.     char GetChar(const int index) {
  48.         if (index < 0 || index >= size) {
  49.             cout << "Invalid index" << endl;
  50.             abort;
  51.         }
  52.         return str[index];
  53.     }
  54.  
  55.     int Size() {
  56.         return size;
  57.     }
  58.  
  59.     int Capacity() {
  60.         return capacity;
  61.     }
  62.  
  63.     ~String() {
  64.         delete[] str;
  65.     }
  66.  
  67. private:
  68.     int size;
  69.     int capacity;
  70.     char* str;
  71. };
  72.  
  73.  
  74. int main() {
  75.     String my_string;
  76.     cout << "Size: " << my_string.Size() << " Capacity: " << my_string.Capacity() << endl;
  77.     my_string.SetString("Hello");
  78.     cout << my_string.GetString() << endl;
  79.     cout << "Size: " << my_string.Size() << " Capacity: " << my_string.Capacity() << endl;
  80.     my_string.SetString("Hello my dear friend");
  81.     cout << my_string.GetString() << endl;
  82.     cout << "Size: " << my_string.Size() << " Capacity: " << my_string.Capacity() << endl;
  83.     my_string.SetChar(2, 'm');
  84.     cout << my_string.GetString() << endl;
  85.     cout << my_string.GetChar(1) << endl;
  86.     String my_new_string("1234");
  87.     cout << my_new_string.GetString() << endl;
  88.     cout << "Size: " << my_new_string.Size() << " Capacity: " << my_new_string.Capacity() << endl;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement