LearnFrenzy
Sign in Take a free test

Strings · String Programs · Question 8

Run-length encoding of a string in C Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

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.

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!

Post your comment

Comments appear after a quick review by our team.

Popular