Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- static int str_in(char *p, int size) {
- if (!fgets(p, size, stdin)) {
- return 0;
- }
- int len = 0;
- for (; *p; ++p, ++len) {
- if (*p == '\n') {
- *p = '\0';
- break;
- }
- if (*p < ' ' || ('0' <= *p && *p <= '9') || '~' < *p) {
- return 0;
- }
- }
- return len;
- }
- static void compress_sub(char **to, char prev, int *len, int c) {
- if (2 < c) {
- **to = '0' + c;
- ++*to;
- ++*len;
- } else {
- for (--c; c; --c, **to = prev, ++*to, ++*len) {
- ;
- }
- }
- }
- static int compress(char *from, char *to) {
- char prev = *to++ = *from++;
- int len = 1, c = 1;
- for (; *from; ++from) {
- if (prev == *from && c < 9) {
- ++c;
- continue;
- }
- compress_sub(&to, prev, &len, c);
- prev = *to++ = *from;
- ++len;
- c = 1;
- }
- compress_sub(&to, prev, &len, c);
- *to = '\0';
- return len;
- }
- static void decompress(char *from, char *to) {
- char prev = *to++ = *from++;
- int len = 1;
- for (; *from; ++from) {
- if (*from < '0' || '9' < *from) {
- prev = *to++ = *from;
- ++len;
- continue;
- }
- for (int c = *from - '0' - 1; c; --c, *to++ = prev, ++len) {
- ;
- }
- }
- *to = '\0';
- // return len;
- }
- int main(void) {
- #define N 16
- char src[N], dest[N], cmp[N];
- if (!str_in(src, N)) {
- return 1;
- }
- #undef N
- printf("|%s| --> ", src);
- compress(src, dest);
- printf("|%s| --> ", dest);
- decompress(dest, cmp);
- printf("|%s| ", cmp);
- printf("%d\n", strcmp(src, cmp));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement