I have a c program which does the string compression successfully in c language and it's a brute force approach there in C language.for example if input is aabccccdddddddddddaa then output should be a2b1c3d11a2.
I solved this in c language by taking each character and counting number of its occurrences and then printing that character and it's count.
I am trying to convert this to c# language. I am wondering it should be easy to do in the c# language because of so many string and char built in methods.
Is there a way we can do this in c# by using lambda expressions or built in methods of string or char type in very few lines?
My C code is :
char *encode(char *src)
{
int recurringLen;
char count[MAX_RLEN];
char *dest;
int i, j = 0, k;
int len = strlen(src);
// _itoa_s(34,c,10);
/* If all characters in the source string are different,
then size of destination string would be twice of input string.
For example if the src is "abcd", then dest would be "a1b1c1d1"
For other inputs, size would be less than twice.
test for the scenarios where abababababababababababa bcos output here is a16b11.
aabbbcccd
*/
dest = (char *)malloc(sizeof(char)*(len*2 + 1));
/* traverse the input string one by one */
for(i = 0; i < len; i++)
{
/* Copy the first occurrence of the new character */
dest[j++] = src[i];
/* Count the number of occurrences of the new character */
recurringLen = 1;
while(i + 1 < len && src[i] == src[i+1])
{
recurringLen++;
i++;
}
/* Store rLen in a character array count[] */
sprintf_s(count, "%d", recurringLen);
/* Copy the count[] to destination */
for(k = 0; *(count+k); k++, j++)
{
dest[j] = count[k];
}
}
/*terminate the destination string */
dest[j] = '\0';
return dest;
}