Question: You are given a string like "aaaabbbcc", do an in place conversion which write frequency of each charater(which come continuosly) with that character. If character repeats only once don't write '1'.


Example:
input: aaabbbcc
output: a3b2c2

input: aabaa
output: a2ba2

Answer:

Answer is very simple but I am puting it here because generally candidates assume that a character can't come more than 9 tims and use freq+'0' to write its frequency. They fail if input is like "aaaaaaaaaa" then their outpur comes as "a:" 9 in place of "a10".

Code:

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

char* strr;
char* itoax(int n)
{
char *temp;
int i;
strr = (char*)malloc(10*sizeof(char));
temp = strr;
for(i=n; i>0; i=i/10)
*strr++ = '0'+ i%10;
*strr = '\0';
temp = strrev(temp);
return temp;
}

void main()
{
char in[100], out[100] = {0};
char *countarr;
int i, j, len, count;
i=j=count=0;

printf("Enter string: ");
scanf("%s", in);
len = strlen(in);

out[i] = in[j];
count = 1;

for(i=1,j=1;i<len;i++,j++)
{
while(in[i] == in[i-1])
{
count ++;
i++;
}
if (count > 1)
{
countarr = itoax(count);
strcat(out,countarr);
j+=strlen(countarr);
count=1;
}
out[j] = in [i];
}

out[j] = '\0';
printf("\n%s\n",out);
}

Subscribe - To get an automatic feed of all future posts subscribe here, or to receive them via email go here and enter your email address in the box. You can also like us on facebook and follow me on Twitter @akashag1001.