Inplace run length encoding of a string

#include <stdio.h>
#include <string.h>

/*
 * variables
 * s : pointer pointing to the free slot
 * q : pointer pointing to the starting of the current running character
 * p : iterator
 */
void runlength(char *s)
{
if(!s || !*s)
return;

char *q = s, *p = s;

int len;

/*iterate while current running character not equal to '' character */
while(*q != '')
{
/* Advance p while current running character repeats */
while(*++p == *q);

/* place the running character in free slot */
*s++ = *q;

/* run length */
len = p - q;

/* print the run length */
if(len > 1)
{
if(len < 10)
*s++ = len + '0';
else
s += sprintf(s, "%d", len);
}

/*Point q to next character */
q = p;
}

/*Place '' at the end of s */
*s = '';
}



main()
{
char s[64];

scanf("%s", s);

runlength(s);

printf("%s\n", s);
}
Advertisements

5 thoughts on “Inplace run length encoding of a string

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s