35657

Untitled

Feb 22nd, 2024
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. #define _CRT_SECURE_NO_WARNINGS
  2.  
  3. #include <iostream>
  4.  
  5. using namespace std;
  6.  
  7. class String {
  8.  
  9. public:
  10.  
  11.     String() {
  12.         size_ = 0;
  13.         capacity_ = 15;
  14.         str_ = new char[capacity_];
  15.     }
  16.  
  17.     String(const int string_capacity) {
  18.         size_ = 0;
  19.         capacity_ = string_capacity;
  20.         str_ = new char[capacity_];
  21.     }
  22.  
  23.     String(const char* new_string) {
  24.         capacity_ = strlen(new_string) + 1;
  25.         str_ = new char[capacity_];
  26.         strcpy(str_, new_string);
  27.         size_ = capacity_ - 1;
  28.     }
  29.  
  30.     void set_string(const char* new_string) {
  31.         int new_space = strlen(new_string) + 1;
  32.         if (capacity_ < new_space) {
  33.             delete[] str_;
  34.             capacity_ = new_space;
  35.             str_ = new char[capacity_];
  36.         }
  37.         strcpy(str_, new_string);
  38.         size_ = capacity_ - 1;
  39.     }
  40.  
  41.     const char* get_string() {
  42.         return str_;
  43.     }
  44.  
  45.     void set_char(const int index, const char ch) {
  46.         if (index < 0 || index >= size_) {
  47.             cout << "Некорректный индекс" << endl;
  48.             return;
  49.         }
  50.         str_[index] = ch;
  51.     }
  52.  
  53.     char get_char(const int index) {
  54.         if (index < 0 || index >= size_) {
  55.             cout << "Некорректный индекс" << endl;
  56.             // здесь функция возвращает char поэтому выйти по return не получится, использовать abort() можно, но тоже не лучший выход, пока пусть будет так, потом обработаем эту ситуацию с помощью исключений
  57.         }
  58.         return str_[index];
  59.     }
  60.  
  61.     int size() {
  62.         return size_;
  63.     }
  64.  
  65.     int capacity() {
  66.         return capacity_;
  67.     }
  68.  
  69.     ~String() {
  70.         delete[] str_;
  71.     }
  72.  
  73.  
  74. private:
  75.     char* str_;
  76.     int size_;
  77.     int capacity_;
  78. };
  79.  
  80.  
  81. int main() {
  82.     setlocale(LC_ALL, "ru");
  83.  
  84.     String str1;
  85.  
  86.     String str2(30);
  87.  
  88.     String str3("Привет");
  89.  
  90.     cout << str3.get_string() << endl;
  91.  
  92.     str3.set_string("Новая строка");
  93.  
  94.     cout << str3.get_string() << endl;
  95.  
  96.     str1.set_string("Еще одна новая строка");
  97.  
  98.     cout << str1.get_string() << endl;
  99. }
  100.  
Add Comment
Please, Sign In to add comment