usaa19exam/rlc.c

105 lines
2.1 KiB
C
Raw Normal View History

2019-12-17 15:38:15 +00:00
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define LINE_SIZE 150
#define MAX_RLEN 50
char* read_line();
char* runLengthCod(char* line);
char* encode(char* src);
char* decode(char* line);
int main(){
char* line = read_line();
//char* compressedline = runLengthCod(line);
char* compressedline = encode(line);
char* decompressedline = decode(compressedline);
printf("line = %s\n", line);
printf("encoded line = %s\n", compressedline);
printf("decoded line = %s\n", decompressedline);
free(line); free(compressedline);
free(decompressedline);
return 1;
}
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;
char ch;
for (i = 0; i < len; i++) {
//dest[j++] = src[i];
ch = 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++]=ch;
}
dest[j] = '\0';
return dest;
}
char* decode(char* line){
char* result = (char*)malloc(LINE_SIZE);
memset(result,0,LINE_SIZE);
int enlen = strlen(line);
int count=0;
int j=0;
for(int i=0; i<enlen; i++){
if(isdigit(line[i])){
count = count*10 + line[i]-'0';
}else{
while(count > 0){
result[j] = line[i];
j++;
count--;
}
}
}
return result;
}
char* read_line(){
char* line=(char*)malloc(LINE_SIZE);
memset(line,0,LINE_SIZE);
char* r = fgets(line,LINE_SIZE,stdin);
if(r==NULL||strlen(line)==1){
free(line);
return 0;
}
else if (strlen(line)==LINE_SIZE-1 && line[LINE_SIZE]!='\n')
{
printf("string is too long\n");
}
else{
int len = strlen(line);
line[len-1] = '\0';
return line;
}
}