Advertisement
vencinachev

Ex1-Corrected

Apr 19th, 2021
907
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.01 KB | None | 0 0
  1. #include <iostream>
  2. #include <cstring>
  3.  
  4. using namespace std;
  5.  
  6. char* stringCompress(const char *str)
  7. {
  8.     char *result = new char[1];
  9.     result[0] = '\0';
  10.     char numbuff[10]; // buffer for number (count)
  11.     char buff[11];    // buffer for number + char
  12.     char current;
  13.     int cnt = 0;
  14.     int i = 0;
  15.     while(*(str + i))
  16.     {
  17.         char current = str[i];
  18.         do
  19.         {
  20.             i++;
  21.             cnt++;
  22.         }
  23.         while (str[i] == current);
  24.  
  25.         itoa(cnt, numbuff, 10);
  26.         cnt = 0;
  27.         sprintf(buff, "%s%c", numbuff, current);
  28.         char *b = result;
  29.         result = new char[strlen(result) + strlen(buff) + 1];
  30.         strcpy(result, b);
  31.         delete[] b;
  32.         strcat(result, buff);
  33.     }
  34.     return result;
  35. }
  36.  
  37. int main()
  38. {
  39.     char* text1 = stringCompress("AAABBCCCC");
  40.     cout << text1 << endl;
  41.     char* text2 = stringCompress("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWBWWWWWWWWWWWWW");
  42.     cout << text2 << endl;
  43.     return 0;
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement