Advertisement
zhukov000

string processing

Feb 23rd, 2020
248
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.20 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. #define DEFAULT_LEN 1000
  6.  
  7. void process_string(char * str, int len_str)
  8. {
  9.   char words[30][12] = {0}; // заполним нулями
  10.   int cnt = 0, j = 0; // cnt - количество слов, j - длина текущего слова
  11.   // разбиваем по словам
  12.   for(int i=0; i < len_str; ++i)
  13.   {
  14.     if ((str[i] == ' ' || str[i] == '.') && i > 0 && str[i-1] != ' ')
  15.     {
  16.       cnt ++;
  17.       j = 0;
  18.     }
  19.     else
  20.     {
  21.       if (str[i] != ' ')
  22.       {
  23.         words[cnt][j] = str[i];
  24.         ++j;
  25.       }
  26.     }
  27.   }
  28.   // обработка и вывод по словам
  29.   printf("Words:\n");
  30.   for(int i=0; i<cnt-1; ++i)
  31.   {
  32.     if ( strcmp(words[i], words[cnt-1]) ) // strcmp = 0, если строки равны
  33.     {
  34.       int m = strlen(words[i]); // длина строки
  35.       // преобразование строки
  36.       char first = words[i][0];
  37.       for(int j=0; j<m-1; ++j)
  38.         words[i][j] = words[i][j+1];
  39.       words[i][m-1] = first;
  40.       // вывод
  41.       printf("%s\n", words[i]);
  42.     }
  43.   }
  44. }
  45.  
  46. // прочитать строку
  47. int read_string(char * str)
  48. {
  49.   int str_size = DEFAULT_LEN;
  50.   int len_str = 0;
  51.   while(1)
  52.   {
  53.     str[len_str] = getchar();
  54.     ++len_str;
  55.     if (len_str == str_size - 1)
  56.     { // если размер строки привысил выделенный размер, то выделить еще 500
  57.       str_size += DEFAULT_LEN / 2;
  58.       str = (char *) realloc(str, str_size);
  59.     }
  60.     if (str[len_str-1] == '.') // если ".", то закончить ввод
  61.     {
  62.       str[len_str] = 0; // отмечаем, что строка окончилась
  63.       str = (char *) realloc(str, len_str + 1); // освобождаем ненужную память
  64.       break;
  65.     }
  66.   }
  67.   return len_str;
  68. }
  69.  
  70. int main()
  71. {
  72.   char * str = (char *) calloc(DEFAULT_LEN, sizeof(char));;
  73.   int len_str = read_string(str);
  74.   // вызов функции обработки строки
  75.   process_string(str, len_str);
  76.   // вывод исходной строки
  77.   printf("\nSource string: %s\n\n", str);
  78.   free(str);
  79.   return 0;
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement