Spooferman Spooferman - 1 month ago 8
C Question

How to compress a string and replace duplicates with its count using C?

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;

}

Answer

A slightly modified version:

char* StrCompress(char myStr[])
{
  char *s, *in;
  for (s = myStr, in = myStr; *s; s++) {
    int count = 1;
    in[0] = s[0]; in++;
    while (s[0] == s[1]) {
      count++;
      s++;
    }   
    if (count > 1) {
      int len = sprintf(in, "%d", count);
      in += len;
    }   
  }
  in[0] = 0;
  return myStr;
}

Additionally, you should not use the address of operator when calling with an array name:

StrCompress(myStr); // not StrCompress(&myStr)

If you are assuming that a character can't repeat more then 9 times, then you can use in[0] = '0' + count instead of the sprintf stuff:

if (count > 1) {
  in[0] = '0' + count;
  in++;
}