简体   繁体   中英

Compression And Decompression

Using C language I've compressed a string like-> aaaabbbbbbccccc into a4b6c5 , now I want to decompress a4b6c5 into aaaabbbbbbccccc . I've tried but I'm unable to do this decompression. Please help me out guys.

#include<stdio.h>
void compress(char*stng);

int main(){
    char stng[50000];
    printf("Enter the String :");  
    scanf("%s",stng);
    compress(stng);
   return 0; 
}

void compress(char*stng)
{  

    int i=0,count=0;  
    char c=stng[i];  

    while(stng[i]!='\0')
    {  
        if(c==stng[i])
            count++; 
        else
        { 
            printf("%c%d",c,count);  c=stng[i];  count=1;  
        }
        i++;  
    }

    printf("%c%d\n",c,count); 
}
#include <stdio.h>

void decompress(const char* code)
{
    while(*code)
    {
        char c = *code++;   // Get the letter to be repeated
        int rep = 0;
        while(isdigit(*code))
        {
            rep = rep*10 + *code++ - '0';  // Get the number of times to repeat the letter
        }
        char set[rep];
        printf("%.*s", rep, memset(set, c, rep));  // Print letter [c], repeated [rep] times
    }
}


int main(void)
{
    char* code = "A4B5C6";
    decompress(code);   
    return 0;
}

Assuming you will never need to have a numeric embedded in the string, this will work. I just did it as old string/new string, but you can adapt it however works best for you.

`

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

int main(int argc, char **argv[])
{
    char            szOldStr[] = "a5b11c6";
    char            szNewStr[128];

    int         iStrLen;
    int         iNumChars;
    int         iOldIndex;
    int         iNewIndex;


    iStrLen = strlen(szOldStr);
    iOldIndex = 0;
    iNewIndex = 0;

    while (szOldStr[iOldIndex])
    {
        // Look for a number, which would represent a compressed character
        if (isdigit(szOldStr[iOldIndex]))
        {
            iNumChars = atoi(szOldStr + iOldIndex);
            // Memset one less character, because we already moved one 
            // into the new string
            memset(szNewStr + iNewIndex, szNewStr[iNewIndex - 1], 
                   iNumChars - 1);  
            iNewIndex += iNumChars - 1;

            // Advance past the number
            while (isdigit(szOldStr[iOldIndex]))
                ++iOldIndex;
        }
        else
        {
            // Not a number, so just move the character to the new string
            szNewStr[iNewIndex] = szOldStr[iOldIndex];
            ++iNewIndex;
            ++iOldIndex;
        }
    }

    // Put a null at the end of our new string
    szNewStr[iNewIndex] = '\0';

    // Show what we created
    puts(szNewStr);
}

`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM