What is “Run Length Encoding (RLE)” ? Write a function, which will accept a string and convert it to a Run Length Encoded string.
Run Length Encoding is way to compress data. It is used when data is repeated multiple times, in such cases rather than storing that many copies of the data, lit stores only one copy of the data and count of the number of times it is repeated.
For example:
Input String: AAAAAAAAAAAABAAAAAAAAAACCCKKKKKKKKKKKKRRRRRRR RLE Encoded String: A12B1A10C3K12R7
Advantages:
This is a lossless data compression technique, because data can be recovered as it was on de-compression.
Algorithm:
Code:
/* Does the RLE of Source (src) and put it in the dest string. * Caller should ensure that the size of dest is sufficient enough * to hold the data */ void encodeRLE(char* src, char* dest) { int i, j, k, runlen; char temp[100]; int srcLen = strlen(src); /* traverse the input string one by one */ for(i=0, j=0; i<srcLen; i++) { dest[j++] = src[i]; // Count the length of Run for(runlen = 1; (i+1 < srcLen) && (src[i] == src[i+1]); runlen++, i++) ; sprintf(temp, "%d", runlen); for(k=0; temp[k]!='\0';) dest[j++] = temp[k++]; } // terminating the dest string dest[j] = '\0'; }