C language string in situ compression method

  • 2020-04-02 02:44:42
  • OfStack

In this paper, an example is given to illustrate the method of in-situ string compression in C language. Share with you for your reference. Specific methods are as follows:

Example of in-situ string compression: "eeeeeaaaff" compressed to "e5a3f2"

The specific function code is as follows:



#include <iostream>
#include <iterator>
#include <algorithm>

using namespace std;

char array[] = "eeeeeaaaff";
char array2[] = "geeeeeaaaffg";
const int size = sizeof array / sizeof *array;
const int size2 = sizeof array2 / sizeof *array2;

void compression(char *array, int size)
{
 int i = 0, j = 0;
 int count = 0;

 while(j < size) {
 count = 0;
 array[i] = array[j];

 while(array[j] == array[i]) {
  count++;
  j++;
 }
 if(count == 1) {
  i++;
 }
 else {
  array[++i] = '0' + count;
  ++i;
 }
 }
 array[i] = 0; 
}

void main()
{
 compression(array, size);
 cout << array << endl;
 compression(array2, size2);
 cout << array2 << endl;
}

It is believed that this paper has certain reference value to the learning of C program algorithm design.


Related articles: