Advertisement
Solingen

Untitled

Oct 6th, 2024
28
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.26 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. using namespace std;
  5.  
  6. class String {
  7.     char* str;  // Строка (динамически выделенная память)
  8.     int len;    // Длина строки
  9.  
  10. public:
  11.     // Конструктор по умолчанию
  12.     String(const char* s = "") {
  13.         len = strlen(s);
  14.         str = new char[len + 1];
  15.         strcpy(str, s);
  16.     }
  17.  
  18.     // Конструктор копирования
  19.     String(const String& other) {
  20.         len = other.len;
  21.         str = new char[len + 1];
  22.         strcpy(str, other.str);
  23.     }
  24.  
  25.     // Оператор присваивания
  26.     String& operator=(const String& other) {
  27.         if (this != &other) {
  28.             delete[] str;
  29.             len = other.len;
  30.             str = new char[len + 1];
  31.             strcpy(str, other.str);
  32.         }
  33.         return *this;
  34.     }
  35.  
  36.     // Деструктор
  37.     ~String() {
  38.         delete[] str;
  39.     }
  40.  
  41.     // Метод для получения длины строки
  42.     int length() const {
  43.         return len;
  44.     }
  45.  
  46.     // Метод substring для получения подстроки
  47.     String substring(int start, int end) const {
  48.         char* buffer = new char[end - start + 1];
  49.         for (int i = start; i < end; ++i) {
  50.             buffer[i - start] = str[i];
  51.         }
  52.         buffer[end - start] = '\0';
  53.         return String(buffer);
  54.     }
  55.  
  56.     // Метод contains для проверки наличия символа в строке
  57.     bool contains(char ch, const String& delimeters) const {
  58.         for (int i = 0; i < delimeters.len; ++i) {
  59.             if (delimeters.str[i] == ch) {
  60.                 return true;
  61.             }
  62.         }
  63.         return false;
  64.     }
  65.  
  66.     // Метод split для разделения строки по разделителям
  67.     class WordIterator split(const String& delimeters = " \t\n") const;
  68.  
  69.     // Оператор вывода
  70.     friend ostream& operator<<(ostream& os, const String& s) {
  71.         os << s.str;
  72.         return os;
  73.     }
  74. };
  75.  
  76. // Структура для хранения слова и указателя на следующий элемент
  77. struct ListItem {
  78.     String word;           // Слово
  79.     ListItem* next;        // Указатель на следующий элемент списка
  80.  
  81.     ListItem(const String& w, ListItem* n = nullptr) : word(w), next(n) {}
  82. };
  83.  
  84. // Класс WordIterator для итерации по списку слов
  85. class WordIterator {
  86.     ListItem* head;       // Указатель на первый элемент списка
  87.     ListItem* current;    // Указатель на текущее слово
  88.     int count;            // Общее количество слов
  89.  
  90. public:
  91.     // Конструктор
  92.     WordIterator(ListItem* h) : head(h), current(h), count(0) {
  93.         // Подсчитываем количество элементов
  94.         ListItem* temp = h;
  95.         while (temp) {
  96.             count++;
  97.             temp = temp->next;
  98.         }
  99.     }
  100.  
  101.     // Возвращает текущее слово
  102.     const String& current_word() const {
  103.         return current->word;
  104.     }
  105.  
  106.     // Переход к следующему слову
  107.     bool next() {
  108.         if (current && current->next) {
  109.             current = current->next;
  110.             return true;
  111.         }
  112.         return false;
  113.     }
  114.  
  115.     // Перемещает итератор на первое слово
  116.     void begin() {
  117.         current = head;
  118.     }
  119.  
  120.     // Возвращает количество слов
  121.     int get_count() const {
  122.         return count;
  123.     }
  124.  
  125.     // Деструктор для удаления динамического списка
  126.     ~WordIterator() {
  127.         while (head) {
  128.             ListItem* temp = head;
  129.             head = head->next;
  130.             delete temp;
  131.         }
  132.     }
  133. };
  134.  
  135. // Реализация метода split
  136. WordIterator String::split(const String& delimeters) const {
  137.     ListItem* head = nullptr;
  138.     ListItem* tail = nullptr;
  139.  
  140.     int start = 0;
  141.     for (int i = 0; i <= len; ++i) {
  142.         // Если найден разделитель или достигнут конец строки
  143.         if (i == len || contains(str[i], delimeters)) {
  144.             if (i > start) {
  145.                 // Получаем слово между start и i
  146.                 String word = substring(start, i);
  147.  
  148.                 // Создаём новый элемент списка
  149.                 ListItem* newItem = new ListItem(word);
  150.                 if (!head) {
  151.                     head = newItem;
  152.                 } else {
  153.                     tail->next = newItem;
  154.                 }
  155.                 tail = newItem;
  156.             }
  157.             start = i + 1;  // Переходим к следующему слову
  158.         }
  159.     }
  160.  
  161.     return WordIterator(head);  // Возвращаем итератор по списку слов
  162. }
  163.  
  164. int main() {
  165.     String s = "Hello \tworld 2024!\n\n";
  166.  
  167.     // Разделяем строку
  168.     WordIterator it = s.split();
  169.  
  170.     // Выводим слова
  171.     do {
  172.         cout << it.current_word() << endl;
  173.     } while (it.next());
  174.  
  175.     return 0;
  176. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement