Compress a string by run-length encoding: "aaabbcddddd" becomes "a3b2c1d5". Never overflow the output buffer.
Solution
main.c
#include <stdio.h>
void rle(const char *s, char *out, size_t size) {
size_t used = 0;
out[0] = '\0';
while (*s && used < size) {
char c = *s;
int run = 0;
while (*s == c) {
s++;
run++;
}
int w = snprintf(out + used, size - used, "%c%d", c, run);
if (w < 0)
break;
used += (size_t) w;
}
}
int main(void) {
char out[32];
rle("aaabbcddddd", out, sizeof out);
printf("%s\n", out);
return 0;
}
Output Verified by compiling and running
a3b2c1d5
Count each run of equal characters, then append "character + count" with snprintf(), which is told how much room is left. If the output fills up, used reaches size and the loop stops instead of overflowing.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!