I need to write a function which will take a string as input and outputs as below
input : aaabbdd
output : a3b2d2
input : aaaaaaaaaaaaaaaabbccc
output : a16b2c3
basically I have to append the count to every character. I should not use itoa() to convert int to string
I wrote the logic. But I got struck at appending the number to the string. For example, if count is 16, how can I add the number 16 to end of a string?
My logic is as given below.
#include <stdio.h>
void str1(char *str)
{
int i, j, cnt;
int len = strlen(str);
char *nstr = (char *) malloc(len * sizeof(char));
int k = 0;
cnt = 1;
for(i = 0, j = 1; i < len - 1;)
{
if(str[i] == str[j])
{
j++;
cnt++;
continue;
}
else
{
if(cnt == 1)
{
nstr[k++] = str[i];
}
else
{
nstr[k++] = str[i];
nstr[k++] = cnt; // GOT STUCK HERE
}
i = j;
j = i + 1;
cnt = 1;
}
}
printf("\n%s\n", nstr);
}
main()
{
char str[] = "aaaaaaaaaaaaaaaabbcdd";
str1(str);
}