#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// dst needs to at least strlen(src)*2+1 in size.
void encode(char* dst, const char* src) {
while (1) {
char ch = *src;
if (!ch) {
*dst = 0;
return;
}
size_t count = 1;
while (*(++src) == ch)
++count;
*(dst++) = ch;
dst += sprintf(dst, "%zu", count);
}
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "usage\n");
return 1;
}
const char* src = argv[1];
char* dst = malloc(strlen(src)*2+1);
encode(dst, src);
printf("%s\n", dst);
free(dst);
return 0;
}
$ gcc -Wall -Wextra -pedantic -std=c99 -o a a.c
$ ./a aabccccccggeeecccccd
a2b1c6g2e3c5d1
$ ./a abc
a1b1c1
7
solved How to reformat code to output properly?