Advertisement
Toliak

something_on_pure_c

Nov 24th, 2018
327
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. void removeTrash(char *str)
  6. {
  7.     unsigned int shift = 0;         // Сдвиг символов
  8.     unsigned int size = 0;          // Размер результата
  9.     unsigned int index = 1;         // Индекс в исходной строке
  10.     char c = str[0];                // Текущий символ
  11.     while (c != '\0') {
  12.         if (c == ' ' || c == '\t') {    // Встретили разделитель
  13.             shift++;                // Увеличиваем сдвиг
  14.         } else {
  15.             if (shift > 0)          // Сдвиг есть?
  16.                 str[index - shift - 1] = c;
  17.             size++;                 // +размер
  18.         }
  19.         c = str[index++];           // Новый символ и индекс
  20.     }
  21.  
  22.     realloc(str, size + 1);         // size + размер ноль-символа
  23.     str[size] = '\0';               // Заверщшаем строку корректно
  24. }
  25.  
  26. unsigned int read(char **array)
  27. {
  28.     unsigned int index = 0;         // Индекс
  29.     while(1) {
  30.         char *str = (char *)malloc(256);    // Строка (динамически выделили в куче)
  31.         gets(str);                          // Читаем
  32.         if (str[0] == '.')                  // Считали .?
  33.             break;
  34.  
  35.         removeTrash(str);                   // Поехали удалять и размер менять
  36.         array[index++] = str;               // Дописываем
  37.     }
  38.  
  39.     return index;                           // Размер
  40. }
  41.  
  42. void write(char **array, unsigned int size)
  43. {
  44.     for (int i = 0; i < size; i++) {
  45.         printf(array[i]);
  46.         printf("\n");
  47.     }
  48. }
  49.  
  50. int main()
  51. {
  52.     char **array = (char **)malloc(sizeof(char *) * 32);
  53.     unsigned int size = read(array);
  54.     realloc(array, sizeof(char *) * size);          // Уменьшаем размер
  55.  
  56.     write(array, size);                             // Пошли печатать
  57.  
  58.     for (int i = 0; i < size; i++) {                // Осторожно, очистка памяти
  59.         free(array[i]);
  60.     }
  61.     free(array);
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement