C Program to Compress the Given String

Given a string, write a program to compress the given string.

Example 1: “aaaabbbcc”
The compressed string is a4b3c2

Example 2: “abcd”
The compressed string is a1b1c1d1

Input Format
The input contains a string

Output Format
Print the encoded string

Constraint
1<=Length<=200
Alter the original string

Sample Input 1

finemind

Sample Output 1

f1i1n1e1m1i1n1d1

Code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_RLEN 50
 
char* encode(char* src)
{
    int rLen;
    char count[MAX_RLEN];
    int len = strlen(src);
 

    char* dest = (char*)malloc(sizeof(char) * (len * 2 + 1));
 
    int i, j = 0, k;
 
    for (i = 0; i < len; i++) {
 
        dest[j++] = src[i];
 
        rLen = 1;
        while (i + 1 < len && src[i] == src[i + 1]) {
            rLen++;
            i++;
        }
 
        sprintf(count, "%d", rLen);
 
        for (k = 0; *(count + k); k++, j++) {
            dest[j] = count[k];
        }
    }
 
    dest[j] = '\0';
    return dest;
}
 
int main()
{
    char str[100];
    scanf("%s",str);
    char* res = encode(str);
    printf("%s", res);
    getchar();
}
Code language: C/AL (cal)

Leave a Comment