C language string fast compression algorithm code

  • 2020-04-02 03:02:03
  • OfStack

Enter a string of lowercase letters (a~z) on the keyboard.
Please write a string compression program to compress the repeated letters in the string and output the compressed string.

Compression rules:

1. Compress only continuously repeated characters. For example, the string "abcbc" is still "abcbc" after compression due to the lack of consecutive repeated characters.
2, the format of the compressed field is "the number of repeated characters + characters". For example, the string "xxxyyyyyyz" is compressed to become "3x6yz".

The sample

Input: "cccddecc" output: "3c2de2c"
Input: "adef" output: "adef"
Input: "PPPPPPPP" output: "8p"

Mainly speaking is the string processing class problem, mainly involves:

1. Input and output of string;
2. The basic commonly used C language string function use;
3. Consideration of multiple cases;
4. Convert Numbers into strings and concatenate them;


#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
int main() 

    char str[100] = {'0'}; 
    char res[100] = {'0'}; 
    scanf("%s",str); 
    int length = strlen(str); 
    int i=0, j=0, k=0; 
    int count = 0; 
    do 
    { 
        if(i < length && str[i++] == str[j]) 
            count++; 
        if(str[i] != str[j]) 
        { 
            if(count <= 1) 
                res[k++] = str[j]; 
            else 
            { 
                if(count > 1) 
                { 
                    char temp[10] = {'0'}; 
                    itoa(count,temp,10); 
                    strcpy(res+k,temp); 
                    k+=strlen(temp); 
                    res[k++] = str[j]; 
                } 
            } 
            j = i; 
            count = 0; 
        } 
    }while(i<length); 
    res[k] = '0'; 
    printf("The result is : %sn",res); 
    return 0; 

The above is the article to share with you all the string compression algorithm content, hope to help you learn C language.


Related articles: