Title: String compression
Enter a string of lowercase letters (A~Z) through the keyboard. Write a string compression program that compresses the repeating letters of successive attendance in a string and outputs the compressed string.
Compression Rules:
1. Compress only consecutive occurrences of characters. For example, the string "ABCBC" because there is no continuous repetition of characters, the compressed string is still "ABCBC".
2. The format of the compressed field is "number of characters repeat + characters". For example: the string "XXXYYYYYYZ" is compressed and becomes "3x6yz"
Required Implementation functions:
void Stringzip (const char *PINPUTSTR, long Linputlen, Char *poutputstr);
"Input" PINPUTSTR: input string
Linputlen: Input string length
"Output" POUTPUTSTR: output string, space has been opened up, and input string length;
"Note" Only needs to complete the function algorithm, the middle does not need any IO input and output
Example
input: "CCCDDECC" output: "3c2de2c "
input: "adef" output: "Adef "
Input: "PPPPPPPP" output: "8p"
#include <stdio.h> #include <iostream>using namespace std;void stringzip (const char *PINPUTSTR, long Linputlen, Char *poutputstr) {char pre=pinputstr[0]; Char current;//=pinputstr[0]; int j=0; int count=1; for (long int i=1;i<linputlen;++i) {current=pinputstr[i]; if (current!=pre) {if (count!=1) {sprintf (poutputstr+j, "%d%c", Count,pre); while (count!=0) {count/=10; j + +; } j + +; Count=1; } else Poutputstr[j++]=pre; } else {count++; } pre=current; } if (count!=1) {sprintf (poutputstr+j, "%d%c", Count,pre); while (count!=0) {count/=10; j + +; } j + +; Count=1; } else Poutputstr[j++]=pre; poutputstr[j]= ' + ';} int main (int argc, Char *argv[]) {char input[100]; Char output[100]; while (~SCANF ("%s", input)) {Stringzip (Input,strlen (input), output); cout << output << Endl; } return 0;}
Test data:
Cccddecc
Adef
Pppppppp
Results:
Huawei machine Test-string compression