I have a large string char myStr=”AAAABBBCCCCCCDDDEFGHHIJJ”.
I shall pass this string to my string compressing function which should return me the string in below format myStr =”A4B3C6D3EFGH2IJ2″
Also, the new string replacements should happen in the same passed string only. One cannot create a temp array.
Below is my func and am not able to figure out the deletion of duplicates and replacing with its count in the same string.
#include<stdio.h>
#include<string.h>
char* StrCompress(char myStr[])
{
char *s = myStr;
int len = strlen(myStr);
char *in = myStr;
int count =0;
int i=0;
while(*(s) != '\0')
{
if(*(s)==*(s+1))
{
count++;
if(count == 1)
{
in = s;
}
s++;
}
else
{
//myStr[count-1]=count;
memcpy(in+1,s+1,count);
s=in;
count =0;
}
i++;
}
return myStr;
}
int main(){
char myStr[] ="AAAABBBCCCCCEEFGIIJJJKLMNNNNOOO";
printf("Compressed String is : %s\n",StrCompress(&myStr));
return 0;
}
A slightly modified version:
Additionally, you should not use the address of operator when calling with an array name:
If you are assuming that a character can’t repeat more then 9 times, then you can use
in[0] = '0' + countinstead of thesprintfstuff: